Design Patterns and PHP 5

Last week, we began our overview of the object-oriented features of PHP 5. This week, we will start discussing design patterns. This article, the second of several parts, is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616).

A Brief Introduction to Design Patterns

You have likely heard of design patterns, but you might not know what they are. Design patterns are generalized solutions to classes of problems that software developers encounter frequently.

If you’ve programmed for a long time, you have most likely needed to adapt a library to be accessible via an alternative API. You’re not alone. This is a common problem, and although there is not a general solution that solves all such problems, people have recognized this type of problem and its varying solutions as being recurrent. The fundamental idea of design patterns is that problems and their corresponding solutions tend to follow repeatable patterns.

Design patterns suffer greatly from being overhyped. For years I dismissed design patterns without real consideration. My problems were unique and complex, I thought—they would not fit a mold. This was really short-sighted of me.

Design patterns provide a vocabulary for identification and classification of problems. In Egyptian mythology, deities and other entities had secret names, and if you could discover those names, you could control the deities’ and entities’ power. Design problems are very similar in nature. If you can discern a problem’s true nature and associate it with a known set of analogous (solved) problems, you are most of the way to solving it.

To claim that a single chapter on design patterns is in any way complete would be ridiculous. The following sections explore a few patterns, mainly as a vehicle for showcasing some of the advanced OO techniques available in PHP.

{mospagebreak title=The Adaptor Pattern}

The Adaptor pattern is used to provide access to an object via a specific interface. In a purely OO language, the Adaptor pattern specifically addresses providing an alternative API to an object; but in PHP we most often see this pattern as providing an alternative interface to a set of procedural routines.

Providing the ability to interface with a class via a specific API can be helpful for two main reasons:

  • If multiple classes providing similar services implement the same API, you can switch between them at runtime. This is known as polymorphism. This is derived from Latin: Poly means “many,” and morph means “form.”

  • A predefined framework for acting on a set of objects may be difficult to change. When incorporating a third-party class that does not comply with the API used by the framework, it is often easiest to use an Adaptor to provide access via the expected API.

The most common use of adaptors in PHP is not for providing an alternative interface to one class via another (because there is a limited amount of commercial PHP code, and open code can have its interface changed directly). PHP has its roots in being a procedural language; therefore, most of the built-in PHP functions are procedural in nature. When functions need to be accessed sequentially (for example, when you’re making a database query, you need to use mysql_pconnect(), mysql_select_db(), mysql_query(), and mysql_fetch()), a resource is commonly used to hold the connection data, and you pass that into all your functions. Wrapping this entire process in a class can help hide much of the repetitive work and error handling that need to be done.

The idea is to wrap an object interface around the two principal MySQL extension resources: the connection resource and the result resource. The goal is not to write a true abstraction but to simply provide enough wrapper code that you can access all the MySQL extension functions in an OO way and add a bit of additional convenience. Here is a first attempt at such a wrapper class:

class DB_Mysql {
 protected $user;
 protected $pass;
 protected $dbhost;
 protected $dbname;
 protected $dbh;  // Database connection handle

 public function _ _construct($user, $pass,
$dbhost, $dbname) { $this->user = $user; $this->pass = $pass; $this->dbhost = $dbhost; $this->dbname = $dbname; } protected function connect() { $this->dbh = mysql_pconnect($this->dbhost,
$this->user, $this->pass); if(!is_resource($this->dbh)) { throw new Exception; } if(!mysql_select_db($this->dbname, $this->dbh)) { throw new Exception; } } public function execute($query) { if(!$this->dbh) { $this->connect(); } $ret = mysql_query($query, $this->dbh); if(!$ret) { throw new Exception; } else if(!is_resource($ret)) { return TRUE; } else { $stmt = new DB_MysqlStatement($this->dbh,
$query); $stmt->result = $ret; return $stmt; } } }

To use this interface, you just create a new DB_Mysql object and instantiate it with the login credentials for the MySQL database you are logging in to (username, password, hostname, and database name):

$dbh = new DB_Mysql("testuser", "testpass",
"localhost", "testdb"); $query = "SELECT * FROM users WHERE name =
'".mysql_escape_string($name)."'"; $stmt = $dbh->execute($query);

This code returns a DB_MysqlStatement object, which is a wrapper you implement around the MySQL return value resource:

class DB_MysqlStatement {
 protected $result;
 public $query;
 protected $dbh;
 public function _ _construct($dbh, $query) {
  $this->query = $query;
  $this->dbh = $dbh;
  if(!is_resource($dbh)) {
   throw new Exception("Not a valid database
connection"); } } public function fetch_row() { if(!$this->result) { throw new Exception("Query not executed"); } return mysql_fetch_row($this->result); } public function fetch_assoc() { return mysql_fetch_assoc($this->result); } public function fetchall_assoc() { $retval = array(); while($row = $this->fetch_assoc()) { $retval[] = $row; } return $retval; } }

To then extract rows from the query as you would by using mysql_fetch_assoc(), you can use this:

while($row = $stmt->fetch_assoc()) {
 // process row

{mospagebreak title=More on the Adapter Pattern}

The following are a few things to note about this implementation:

  • It avoids having to manually call connect() and mysql_select_db().

  • It throws exceptions on error. Exceptions are a new feature in PHP5. We won’t discuss them much here, so you can safely ignore them for now, but the second half of Chapter 3, “Error Handling,” is dedicated to that topic.

  • It has not bought much convenience. You still have to escape all your data, which is annoying, and there is no way to easily reuse queries.

To address this third issue, you can augment the interface to allow for the wrapper to automatically escape any data you pass it. The easiest way to accomplish this is by providing an emulation of a prepared query. When you execute a query against a database, the raw SQL you pass in must be parsed into a form that the database understands internally. This step involves a certain amount of overhead, so many database systems attempt to cache these results. A user can prepare a query, which causes the database to parse the query and return some sort of resource that is tied to the parsed query representation. A feature that often goes hand-in-hand with this is bind SQL. Bind SQL allows you to parse a query with placeholders for where your variable data will go. Then you can bind parameters to the parsed version of the query prior to execution. On many database systems (notably Oracle), there is a significant performance benefit to using bind SQL.

Versions of MySQL prior to 4.1 do not provide a separate interface for users to prepare queries prior to execution or allow bind SQL. For us, though, passing all the variable data into the process separately provides a convenient place to intercept the variables and escape them before they are inserted into the query. An interface to the new MySQL 4.1 functionality is provided through Georg Richter’s mysqli extension.

To accomplish this, you need to modify DB_Mysql to include a prepare method and DB_MysqlStatement to include bind and execute methods:

class DB_Mysql {
 /* ... */
 public function prepare($query) {
  if(!$this->dbh) {
  return new DB_MysqlStatement($this->dbh, $query);
class DB_MysqlStatement {
 public $result;
 public $binds;
 public $query;
 public $dbh;
 /* ... */
 public function execute() {
  $binds = func_get_args();
  foreach($binds as $index => $name) {
   $this->binds[$index + 1] = $name;
  $cnt = count($binds);
  $query = $this->query;
  foreach ($this->binds as $ph => $pv) {
   $query = str_replace(":$ph",
"'".mysql_escape_string($pv)."'", $query); } $this->result = mysql_query($query, $this->dbh); if(!$this->result) { throw new MysqlException; } return $this; } /* ... */ }

In this case, prepare()actually does almost nothing; it simply instantiates a new DB_MysqlStatement object with the query specified. The real work all happens in DB_MysqlStatement. If you have no bind parameters, you can just call this:

$dbh = new DB_Mysql("testuser", "testpass",
"localhost", "testdb"); $stmt = $dbh->prepare("SELECT * FROM users WHERE name =
'".mysql_escape_string($name)."'"); $stmt->execute();

The real benefit of using this wrapper class rather than using the native procedural calls comes when you want to bind parameters into your query. To do this, you can embed placeholders in your query, starting with :, which you can bind into at execution time:

$dbh = new DB_Mysql("testuser", "testpass",
"localhost", "testdb"); $stmt = $dbh->prepare("SELECT * FROM users WHERE
name = :1"); $stmt->execute($name);

The :1 in the query says that this is the location of the first bind variable. When you call the execute() method of $stmt, execute() parses its argument, assigns its first passed argument ($name) to be the first bind variable’s value, escapes and quotes it, and then substitutes it for the first bind placeholder :1 in the query.

Even though this bind interface doesn’t have the traditional performance benefits of a bind interface, it provides a convenient way to automatically escape all input to a query.

{mospagebreak title=The Template Pattern}

The Template pattern describes a class that modifies the logic of a subclass to make it complete.

You can use the Template pattern to hide all the database-specific connection parameters in the previous classes from yourself. To use the class from the preceding section, you need to constantly specify the connection parameters:

require_once '';

define('DB_MYSQL_PROD_USER', 'test');
define('DB_MYSQL_PROD_PASS', 'test');
define('DB_MYSQL_PROD_DBHOST', 'localhost');
define('DB_MYSQL_PROD_DBNAME', 'test');

$dbh = new DB::Mysql(DB_MYSQL_PROD_USER,
DB_MYSQL_PROD_DBNAME); $stmt = $dbh->execute("SELECT now()"); print_r($stmt->fetch_row()); ?>

To avoid having to constantly specify your connection parameters, you can subclass DB_Mysql and hard-code the connection parameters for the test database:

class DB_Mysql_Test extends DB_Mysql {
 protected $user  = "testuser";
 protected $pass  = "testpass";
 protected $dbhost = "localhost";
 protected $dbname = "test"; 

 public function _ _construct() { }

Similarly, you can do the same thing for the production instance:

class DB_Mysql_Prod extends DB_Mysql {
 protected $user  = "produser";
 protected $pass  = "prodpass";
 protected $dbhost = "";
 protected $dbname = "prod"; 

 public function _ _construct() { }

Please check back next week for the continuation of this article.

Google+ Comments

Google+ Comments