13

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 its 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...

danronmoon
  • 3,814
  • 5
  • 34
  • 56
jerry
  • 2,743
  • 9
  • 41
  • 61
  • What's the point of making `__destruct` do `$this->dbh = null;`, if you don't have the property `this->dbh` defined or used in any way? Every `$this->db_connect();` result is assigned to a local scope's `$dbh` at method scope's level... – SebasSBM Oct 31 '19 at 07:24

2 Answers2

27

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.

David Harkness
  • 35,992
  • 10
  • 112
  • 134
  • So each Domain Object in the Domain Model could/should have a related Dao object for the CRUD operations then? – jerry Jul 01 '12 at 23:54
  • @saddog - Each root-level object, yes. For example, an `Order` and its list of `LineItem` children would likely be stored together through `OrderDao`. Unfortunately, you can rarely *completely* isolate the business logic from how you persist the domain model objects. – David Harkness Jul 02 '12 at 02:31
  • Okay, that actually brings up one more question, and then I'll accept and give you the bounty. You mention LineItem children and I want to make sure I would be handling these correctly in my application. Would these children map to tables in the db (a LineItem table) and just be consolidated in the Order domain object by the Dao? i.e. a createObject method in the DaoUser would be the one to bring these two objects together? – jerry Jul 02 '12 at 10:06
  • Edit: would a createObject method in the OrderDao be where items are consolidated to form the Domain Object? – jerry Jul 02 '12 at 11:27
  • @jerry - Yes, that's correct. This isn't mandatory, but the reasoning is to treat an order and its items as a self-contained object (encapsulation). It also cuts down on the number of DAOs you have to build, even though you can probably generate the code for the basic operations. – David Harkness Jul 02 '12 at 14:44
  • Okay, thanks. It looks like I have to wait another 3 hours before I can award the bounty, but I definitely will. Thanks again for your help. – jerry Jul 02 '12 at 19:26
  • How does a repository fit into this picture? – Ben Jan 08 '14 at 18:42
  • Question: is there a particular set of conventions for function naming inside DAO? i.e. can I use whatever naming scheme with whatever multiple parameters that I choose, like `findProductByMultipleParams($prodId, $specId, $featureId)`? – Dennis Apr 01 '14 at 14:30
0
  1. It's not necessarily necessary, but it's certainly common practice. There are many libraries that abstract waaaaay further than what you're doing :)
Lusitanian
  • 11,012
  • 1
  • 41
  • 38