NotionCommotion Posted August 4, 2015 Share Posted August 4, 2015 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'); } } Quote Link to comment https://forums.phpfreaks.com/topic/297622-sharing-database-connection-between-different-classes/ Share on other sites More sharing options...
gizmola Posted August 4, 2015 Share Posted August 4, 2015 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. Quote Link to comment https://forums.phpfreaks.com/topic/297622-sharing-database-connection-between-different-classes/#findComment-1517997 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.