How could PHP's PDO feature and the DAO pattern be mixed? Should I have an abstract class that initializes a connection to the database? Can PDO be considered as equivalent to Java's JDBC?
Yes, PDO is pretty much the "equivalent" of JDBC but in PHP.
You should pass an instance of PDO in the constructor of your domain objects (dependency injection):
abstract class Object {
protected $_pdo;
protected $_target;
public function __construct(PDO $pdo) {
$this->_pdo = $pdo;
}
public function load($id) {
// $this->_pdo->something()
}
public function save() {
// $this->_pdo->something()
}
public function delete() {
// $this->_pdo->something()
}
}
class User extends Object {
protected $_target = 'user_table';
public $name;
}
Then:
$pdo = new PDO('mysql:dbname=foobar');
$user = new User($pdo);
$user->name = 'netcoder';
$user->save();
You could also add a static method in Object to specify a default instance:
class Object {
// ...
static protected $_defaultPDO;
static public function setDefaultPDO(PDO $pdo) {
self::$_defaultPDO = $pdo;
}
public function __construct(PDO $pdo = null) {
if (!isset($pdo)) $pdo = self::$_defaultPDO;
if (!isset($pdo))
throw new DomainException('No default PDO object defined');
$this->_pdo = $pdo;
}
}
Object::setDefaultPDO(new PDO('mysql:dbname=foobar'));
$user = new User;
$user->name = 'James P.';
$user->save();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With