Документация
HTML CSS PHP PERL другое
A Brief Introduction to Design Patterns
 
Previous
Table of Contents
Next

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

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 Greek: 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
}

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) {
      $this->connect();
    }
    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.

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:

<?php
require_once 'DB.inc';

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_PASS,
                     DB_MYSQL_PROD_DBHOST, 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 = "prod.db.example.com";
  protected $dbname = "prod";

  public function _ _construct() { }
}

Polymorphism

The database wrappers developed in this chapter are pretty generic. In fact, if you look at the other database extensions built in to PHP, you see the same basic functionality over and over againconnecting to a database, preparing queries, executing queries, and fetching back the results. If you wanted to, you could write a similar DB_Pgsql or DB_Oracle class that wraps the PostgreSQL or Oracle libraries, and you would have basically the same methods in it.

In fact, although having basically the same methods does not buy you anything, having identically named methods to perform the same sorts of tasks is important. It allows for polymorphism, which is the ability to transparently replace one object with another if their access APIs are the same.

In practical terms, polymorphism means that you can write functions like this:

function show_entry($entry_id, $dbh)
{
  $query = "SELECT * FROM Entries WHERE entry_id = :1";
  $stmt = $dbh->prepare($query)->execute($entry_id);
  $entry = $stmt->fetch_row();
  // display entry
}

This function not only works if $dbh is a DB_Mysql object, but it works fine as long as $dbh implements a prepare() method and that method returns an object that implements the execute() and fetch_assoc() methods.

To avoid passing a database object into every function called, you can use the concept of delegation. Delegation is an OO pattern whereby an object has as an attribute another object that it uses to perform certain tasks.

The database wrapper libraries are a perfect example of a class that is often delegated to. In a common application, many classes need to perform database operations. The classes have two options:

  • You can implement all their database calls natively. This is silly. It makes all the work you've done in putting together a database wrapper pointless.

  • You can use the database wrapper API but instantiate objects on-the-fly. Here is an example that uses this option:

    class Weblog {
      public function show_entry($entry_id)
      {
        $query = "SELECT * FROM Entries WHERE entry_id = :1";
        $dbh = new Mysql_Weblog();
        $stmt = $dbh->prepare($query)->execute($entry_id);
        $entry = $stmt->fetch_row();
        // display entry
      }
    }
    

    On the surface, instantiating database connection objects on-the-fly seems like a fine idea; you are using the wrapper library, so all is good. The problem is that if you need to switch the database this class uses, you need to go through and change every function in which a connection is made.

  • You implement delegation by having Weblog contain a database wrapper object as an attribute of the class. When an instance of the class is instantiated, it creates a database wrapper object that it will use for all input/output (I/O). Here is a re-implementation of Weblog that uses this technique:

    class Weblog {
      protected $dbh;
      public function setDB($dbh)
      {
        $this->dbh = $dbh;
      }
      public function show_entry($entry_id)
      {
        $query = "SELECT * FROM Entries WHERE entry_id = :1";
        $stmt = $this->dbh->prepare($query)->execute($entry_id);
        $entry = $stmt->fetch_row();
        // display entry
      }
    }
    

Now you can set the database for your object, as follows:

$blog = new Weblog;
$dbh = new Mysql_Weblog;
$blog->setDB($dbh);

Of course, you can also opt to use a Template pattern instead to set your database delegate:

class Weblog_Std extends Weblog {
  protected $dbh;
  public function _ _construct()
  {
    $this->dbh = new Mysql_Weblog;
  }
}
$blog = new Weblog_Std;

Delegation is useful any time you need to perform a complex service or a service that is likely to vary inside a class. Another place that delegation is commonly used is in classes that need to generate output. If the output might be rendered in a number of possible ways (for example, HTML, RSS [which stands for Rich Site Summary or Really Simple Syndication, depending on who you ask], or plain text), it might make sense to register a delegate capable of generating the output that you want.

Interfaces and Type Hints

A key to successful delegation is to ensure that all classes that might be dispatched to are polymorphic. If you set as the $dbh parameter for the Weblog object a class that does not implement fetch_row(), a fatal error will be generated at runtime. Runtime error detection is hard enough, without having to manually ensure that all your objects implement all the requisite functions.

To help catch these sorts of errors at an earlier stage, PHP5 introduces the concept of interfaces. An interface is like a skeleton of a class. It defines any number of methods, but it provides no code for themonly a prototype, such as the arguments of the function. Here is a basic interface that specifies the methods needed for a database connection:

interface DB_Connection {
  public function execute($query);
  public function prepare($query);
}

Whereas you inherit from a class by extending it, with an interface, because there is no code defined, you simply agree to implement the functions it defines in the way it defines them.

For example, DB_Mysql implements all the function prototypes specified by DB_Connection, so you could declare it as follows:

class DB_Mysql implements DB_Connection {
  /* class definition */
}

If you declare a class as implementing an interface when it in fact does not, you get a compile-time error. For example, say you create a class DB_Foo that implements neither method:

<?php
require "DB/Connection.inc";
class DB_Foo implements DB_Connection {}
?>

Running this class generates the following error:

Fatal error: Class db_foo contains 2 abstract methods and must
be declared abstract (db connection::execute, db connection:: prepare)
 in /Users/george/Advanced PHP/examples/chapter-2/14.php on line 3

PHP does not support multiple inheritance. That is, a class cannot directly derive from more than one class. For example, the following is invalid syntax:

class A extends B, C {}

However, because an interface specifies only a prototype and not an implementation, a class can implement an arbitrary number of interfaces. This means that if you have two interfaces A and B, a class C can commit to implementing them both, as follows:

<?php

interface A {
  public function abba();
}

interface B {
  public function bar();
}

class C implements A, B {
  public function abba()
  {
    // abba;
  }
  public function bar()
  {
    // bar;
  }
}
?>

An intermediate step between interfaces and classes is abstract classes. An abstract class can contain both fleshed-out methods (which are inherited) and abstract methods (which must be defined by inheritors). The following example shows an abstract class A, which fully implements the method abba() but defines bar() as an abstract:

abstract class A {
  public function abba()
  {
    // abba
  }
  abstract public function bar();
}

Because bar() is not fully defined, it cannot be instantiated itself. It can be derived from, however, and as long as the deriving class implements all of A's abstract methods, it can then be instantiated. B extends A and implements bar(), meaning that it can be instantiated without issue:

class B { extends A{
  public function bar()
  {
    $this->abba();
  }
}
$b = new B;

Because abstract classes actually implement some of their methods, they are considered classes from the point of view of inheritance. This means that a class can extend only a single abstract class.

Interfaces help prevent you from shooting yourself in the foot when you declare classes intended to be polymorphic, but they are only half the solution to preventing delegation errors. You also need to be able to ensure that a function that expects an object to implement a certain interface actually receives such an object.

You can, of course, perform this sort of computation directly in your code by manually checking an object's class with the is_a() function, as in this example:

function addDB($dbh)
{
  if(!is_a($dbh, "DB_Connection")) {
    trigger_error("\$dbh is not a DB_Connection object", E_USER_ERROR);
  }
  $this->dbh = $dbh;
}

This method has two flaws:

  • It requires a lot of verbiage to simply check the type of a passed parameter.

  • More seriously, it is not a part of the prototype declaration for the function. This means that you cannot force this sort of parameter checking in classes that implement a given interface.

PHP5 addresses these deficiencies by introducing the possibility of type-checking/type hinting in function declarations and prototypes. To enable this feature for a function, you declare it as follows:

function addDB(DB_Connection $dbh)
{
  $this->dbh = $dbh;
}

This function behaves exactly as the previous example, generating a fatal error if $dbh is not an instance of the DB_Connection class (either directly or via inheritance or interface implementation).

The Factory Pattern

The Factory pattern provides a standard way for a class to create objects of other classes. The typical use for this is when you have a function that should return objects of different classes, depending on its input parameters.

One of the major challenges in migrating services to a different database is finding all the places where the old wrapper object is used and supplying the new one. For example, say you have a reporting database that is backed against an Oracle database that you access exclusively through a class called DB_Oracle_Reporting:

class DB_Oracle_Reporting extends DB_Oracle { /* ... */}

and because you had foresight DB_Oracle uses our standard database API.

class DB_Oracle implements DB_Connection { /* ... */ }

Scattered throughout the application code, whenever access to the reporting database is required, you have wrapper instantiations like this:

$dbh = new DB_Oracle_Reporting;

If you want to cut the database over to use the new wrapper DB_Mysql_Reporting, you need to track down every place where you use the old wrapper and change it to this:

$dbh = new DB_Mysql_Reporting;

A more flexible approach is to create all your database objects with a single factory. Such a factory would look like this:

function DB_Connection_Factory($key)
{
  switch($key) {
    case "Test":
      return new DB_Mysql_Test;
    case "Prod":
      return new DB_Mysql_Prod;
    case "Weblog":
      return new DB_Pgsql_Weblog;
    case "Reporting":
      return new DB_Oracle_Reporting;
    default:
      return false;
  }
}

Instead of instantiating objects by using new, you can use the following to instantiate objects:

$dbh = DB_Connection_factory("Reporting");

Now to globally change the implementation of connections using the reporting interface, you only need to change the factory.

The Singleton Pattern

One of the most lamented aspects of the PHP4 object model is that it makes it very difficult to implement singletons. The Singleton pattern defines a class that has only a single global instance. There are an abundance of places where a singleton is a natural choice. A browsing user has only a single set of cookies and has only one profile. Similarly, a class that wraps an HTTP request (including headers, response codes, and so on) has only one instance per request. If you use a database driver that does not share connections, you might want to use a singleton to ensure that only a single connection is ever open to a given database at a given time.

There are a number of methods to implement singletons in PHP5. You could simply declare all of an object's properties as static, but that creates a very weird syntax for dealing with the object, and you never actually use an instance of the object. Here is a simple class that implements the Singleton pattern:

<?php
class Singleton {
  static $property;
  public function _ _construct() {}
}

Singleton::$property = "foo";
?>

In addition, because you never actually create an instance of Singleton in this example, you cannot pass it into functions or methods.

One successful method for implementing singletons in PHP5 is to use a factory method to create a singleton. The factory method keeps a private reference to the original instance of the class and returns that on request. Here is a Factory pattern example. getInstance() is a factory method that returns the single instance of the class Singleton.

class Singleton {
  private static $instance = false;
  public $property;
  private function _ _construct() {}
  public static function getInstance()
  {
    if(self::$instance === false) {
      self::$instance = new Singleton;
    }
    return self::$instance;
  }
}
$a = Singleton::getInstance();
$b = Singleton::getInstance();
$a->property = "hello world";
print $b->property;

Running this generates the output "hello world", as you would expect from a singleton. Notice that you declared the constructor method private. That is not a typo; when you make it a private method, you cannot create an instance via new Singleton except inside the scope of the class. If you attempt to instantiate outside the class, you get a fatal error.

Some people are pathologically opposed to factory methods. To satisfy developers who have such leanings, you can also use the _ _get() and _ _set() operators to create a singleton that is created through a constructor:

class Singleton {
  private static $props = array();

  public function _ _construct() {}
  public function _ _get($name)
  {
    if(array_key_exists($name, self::$props)) {
      return self::$props[$name];
    }
  }
  public function _ _set($name, $value)
  {
    self::$props[$name] = $value;
  }
}

$a = new Singleton;
$b = new Singleton;
$a->property = "hello world";
print $b->property;

In this example, the class stores all its property values in a static array. When a property is accessed for reading or writing, the _ _get and _ _set access handlers look into the static class array instead of inside the object's internal property table.

Personally, I have no aversion to factory methods, so I prefer to use them. Singletons are relatively rare in an application and so having to instantiate them in a special manner (via their factory) reinforces that they are different. Plus, by using the private constructor, you can prevent rogue instantiations of new members of the class.

Chapter 6, "Unit Testing," uses a factory method to create a pseudo-singleton where a class has only one global instance per unique parameter.


Previous
Table of Contents
Next
Главная
php
html
css
web
Веселов
Высоцкий
Искусство
Goryunova
Блок