Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining PDO and DAO pattern

Tags:

php

pdo

dao

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?

like image 670
James P. Avatar asked Apr 06 '26 08:04

James P.


1 Answers

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();
like image 50
netcoder Avatar answered Apr 08 '26 23:04

netcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!