Combining PDO and DAO Models

How can I mix a PHP PDO function and a DAO pattern ? Should I have an abstract class that initializes a database connection? Is PDO the equivalent of Java JDBC?

+3
source share
2 answers

How can I mix a PHP PDO function and a DAO pattern?

Just use pdo to make requests to your dao object.

class PersonDAO {

   function get($id) {
     //> EXECUTE HERE PDO
   }

}

PDO also already abstracts the connection, so you don't need an abstract class to connect.

+3
source

Yes, PDO is pretty much the "equivalent" of JDBC, but in PHP.

You must pass the PDO instance 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();

Object, :

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();
+6

All Articles