Jump to content

Handling DB Connection


Neji

Recommended Posts

I'm in the process of coding  a PDO wrapper class, really as a learning project but want to get it right so I can expand it in the future.

 

Basically, I've written the following constructor to connect to the database:

public function __construct() {

//Set up the Database Source Name
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->name;

// Set up options
$option = array(
PDO::ATTR_PERSISTENT => true
);

// Create a new PDO instance
try {
$this->conn = new PDO($dsn, $this->user, $this->pass, $options);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

// Catch any errors
catch(PDOException $e) {
$this->error = $e->getMessage();
}

}

My question relates to creating a $db object, then using it in my other classes. I've read much about a singleton pattern (how it's best to avoid) and I like the ease of just being able to say DB::Query etc but I'm learning so I want to use best practices. At the moment, I use a factory class for creating objects and then using Dependency Injection to set up objects based on other classes.

 

So I have a couple of questions about the best way to go about this:

 

If I were to continue using my factory class, how do I got about using just one DB connection/object in that file? I had the thought of creating a base class for the factory which enables the DB connection, then setting it as a property so then I can just pass that property into the create object methods. Or when creating objects I could use $db = new Database(); but how do I ensure that I'm just using the one db connection (will my persistent attr in the constructor help there)? Return an instance?

 

Am I going in the right direction or is there a better way?

 

Is having an extrmely easy to use DB object (a singleton approach) actually okay in this instance?

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/277953-handling-db-connection/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.