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');
    }
}

 

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.

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.