Jump to content

Sharing database connection between different classes


NotionCommotion

Recommended Posts

A while back, I used a singleton static class to share my database connection in various classes.  Effectively, it was a global variable.

 

I've since wanted to change my approach, and eliminate most if not all global variables.

 

I am thinking something like the following.  Any problems with this approach, or anything I should do to improve?

 

Thanks

 

$db=new PDO("mysql:host=localhost;dbname=dashboard;charset=utf8mb4",'myusername','mypassword',array(PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC));


$bla1=new bla1($db);
$rs1=$bla1->getIt();


$bla2=new bla2(array('db'=>$db,'x'=>123));
$rs2=$bla2->getIt();


class bla1
{
    private $db;
    public function __construct($db) {
        $this->db=$db;
    }


    public function getIt() {
        $rs=$this->db->query('SELECT 1');
    }
}
class bla2
{
    private $db;
    public $x;
    public function __construct($arr) {
        foreach($arr as $key=>$value) {
            $this->$key=$value;
        }
    }


    public function getIt() {
        $rs=$this->db->query('SELECT 2');
    }
}

 

Link to comment
Share on other sites

This is basically the idea behind the popular idea of class relationships via dependency injection/inversion of control/loose coupling. Nice article by the architect of the symfony framework explaining the idea in more detail here: http://fabien.potencier.org/what-is-dependency-injection.html

 

It's great to start with private variables, but frequently you want to take a step back from that and use protected variables, unless you are certain you will not be using inheritance.

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.