PHP Data Access Object

jerry picture jerry · Jun 29, 2012 · Viewed 19.6k times · Source

I'm trying to figure out if I'm using the DAO pattern correctly and, more specifically, how abstract db persistence should be by the time it gets to my mapper classes. I'm using PDO as the data-access abstraction object, but sometimes I wonder if I'm trying to abstract the queries too much.

I've just included how I'm abstracting select queries, but I've written methods for all of the CRUD operations.

class DaoPDO {

    function __construct() {

        // connection settings
        $this->db_host   = '';
        $this->db_user   = ''; 
        $this->db_pass   = ''; 
        $this->db_name   = '';


    }

    function __destruct() {

        // close connections when the object is destroyed
        $this->dbh = null;

    } 


    function db_connect() {

        try { 

            /**
             * connects to the database -
             * the last line makes a persistent connection, which
             * caches the connection instead of closing it 
             */
            $dbh = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", 
                            $this->db_user, $this->db_pass, 
                            array(PDO::ATTR_PERSISTENT => true));


            return $dbh;

        } catch (PDOException $e) {

            // eventually write this to a file
            print "Error!: " . $e->getMessage() . "<br/>";
            die();

        }


    } // end db_connect()'



    function select($table, array $columns, array $where = array(1=>1), $select_multiple = false) {

        // connect to db
        $dbh = $this->db_connect();

        $where_columns  = array();
        $where_values   = array();

        foreach($where as $col => $val) {

            $col = "$col = ?";

            array_push($where_columns, $col);
            array_push($where_values, $val);

        }


        // comma separated list
        $columns = implode(",", $columns);

        // does not currently support 'OR' arguments
        $where_columns = implode(' AND ', $where_columns);



        $stmt = $dbh->prepare("SELECT $columns
                               FROM   $table
                               WHERE  $where_columns");


        $stmt->execute($where_values);

        if (!$select_multiple) {

            $result = $stmt->fetch(PDO::FETCH_OBJ);
            return $result;

        } else {

            $results = array();

            while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {

                array_push($results, $row);

            }

            return $results;

        }



    } // end select()


} // end class

So, my two questions:

  1. Is this the correct use of a DAO, or am I misinterpreting it's purpose?

  2. Is abstracting the query process to this degree unnecessary, or even uncommon? Sometimes I feel like I'm trying to make things too easy...

Answer

David Harkness picture David Harkness · Jul 2, 2012

It looks more like you're building a persistence abstraction layer on top of PDO (which is itself a persistence layer) rather than a data access object. While there are many forms that a DAO can take, the goal is to separate your business logic from the persistence mechanism.

  Business Logic
        |
        v
Data Access Object
        |
        v
 Persistence Layer

A DAO with db_connect and select is too closely modeled after the persistence layer. The simplest form of a generic DAO is to provide the basic CRUD operations at an object level without exposing the internals of the persistence mechanism.

interface UserDao
{
    /**
     * Store the new user and assign a unique auto-generated ID.
     */
    function create($user);

    /**
     * Return the user with the given auto-generated ID.
     */
    function findById($id);

    /**
     * Return the user with the given login ID.
     */
    function findByLogin($login);

    /**
     * Update the user's fields.
     */
    function update($user);

    /**
     * Delete the user from the database.
     */
    function delete($user);
}

If your business objects are the underlying PDO model objects, you can return them from the DAO. Be aware that depending on the underlying persistence mechanism you choose, this may not be ideal. I haven't worked with PDO but assume it's similar to other ORM tools that produce standard PHP objects without tying the business logic to the PDO API. So you're probably okay here.

If you were implementing persistence by accessing the mysqli library directly, for example, you would want to copy data to/from the result sets into your own model objects. This is the job of the DAO to keep it out of the business logic.

By using an interface for the DAO you can now implement it for different persistence frameworks: PDO, Doctrine, raw SQL, whatever. While you're unlikely to switch methods mid-project, the cost of using an interface is negligible compared to its other benefits, e.g. using a mock in unit testing.