O'Reilly logo

Professional PHP Design Patterns by Aaron Saray

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.3. Code Example

In this example, a user entity is the focus. The user has a row in a MySQL database that contains information specific and unique to each user. The functionality must allow us to return a user by their primary key or by a search on their first name. Additionally, you must be able to perform updates to any field in the user entity's row.

From these requirements, two classes are needed. The first should be the base Data Access Object with methods to fetch data and update data:

abstract class baseDAO
{
    private $__connection;

    public function __construct()
    {
        $this->__connectToDB(DB_USER, DB_PASS, DB_HOST, DB_DATABASE);
    }

    private function __connectToDB($user, $pass, $host, $database)
    {
        $this->__connection = mysql_connect($host, $user, $pass);
        mysql_select_db($database, $this->__connection);
    }

    public function fetch($value, $key = NULL)
    {
        if (is_null($key)) {
            $key = $this->_primaryKey;
        }

        $sql = "select * from {$this->_tableName} where {$key}='{$value}'";
        $results = mysql_query($sql, $this->__connection);

        $rows = array();
        while ($result = mysql_fetch_array($results)) {
            $rows[] = $result;
        }

        return $rows;
    }

    public function update($keyedArray)
    {
        $sql = "update {$this->_tableName} set ";

        $updates = array();
        foreach ($keyedArray as $column=>$value) {
            $updates[] = "{$column}='{$value}'";
        }

        $sql .= implode(',', $updates);
        $sql .= "where {$this->_primaryKey}='{$keyedArray[$this->_primaryKey]}'";

        mysql_query($sql, $this->__connection);
    }
}

The first thing to note is that this ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required