php - How to use PDO with dependency injection? -
i'm having hard time understanding how use dependency injection. i've read on lot of questions/answers here can't picture code i'm using.
model.php
abstract class model { protected static function getdb() { static $db = null; if ($db === null) { $db = new pdo('mysql:host=host;dbname=dbname;charset=utf8', 'dbuser', 'password'); } return $db; } }
the model.php contains function, want move away setting , calling statically.
user.php
class user extends model { /* * selects of user information */ public function getuser($id){ $db = static::getdb(); $sth = $db->prepare('select * user id = :id'); $sth->bindvalue(':id', $id, pdo::param_int); $sth->execute(); return $sth->fetch(); } /* * selects of user posts */ public function getuserposts($id){ $db = static::getdb(); $sth = $db->prepare('select * user_posts user_id = :id'); $sth->bindvalue(':id', $id, pdo::param_int); $sth->execute(); return $sth->fetch(); } }
in user.php i'm extending model class, have set $db = static::getdb();
in every single function.
i know dependency injection pretty passing methods/variables object i'm not sure i'm doing right.
updated further thoughts:
i'm thinking better create private variable, , in constructor we'd call getdb()
so:
class user extends model { protected $db; public function __construct(){ $this->db = getdb(); } /* * example usage */ public function getuser($id){ $sth = $this->db->prepare('select * user id = :id'); $sth->bindvalue(':id', $id, pdo::param_int); $sth->execute(); return $sth->fetch(); } }
but still count dependency injection i'm not calling class directly in function constructor?
second update: after reading multiple guides, , page wound making lot more sense, came with.
model.php
abstract class model { protected $db = null; public function __construct(){ if($this->db === null){ try { $this->db = new pdo('mysql:host=' . config::db_host . ';dbname=' . config::db_name . '; charset=utf8', config::db_user, config::db_password); $this->db->setattribute(pdo::attr_errmode, pdo::errmode_exception); } catch (pdoexception $e) { echo 'connection failed: ' . $e->getmessage(); } } return $this->db; } }
user.php
class user extends model { protected $db; public function __construct(model $db){ $this->db = $db; } /* * example usage */ public function getuser($id){ $sth = $this->db->prepare('select * user id = :id'); $sth->bindvalue(':id', $id, pdo::param_int); $sth->execute(); return $sth->fetch(); } }
how look?
i think not using dependency injection because not supplying dependencies model, generating them on constructor.
in order supply dependency should pass argument constructor:
public function __construct($db){ $this->db = $db; }
this way decouple creation of connection class , can use benefits of dependency injection, passing mock object testing instead of actual thing.
Comments
Post a Comment