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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.