{"id":458,"date":"2013-03-06T04:41:47","date_gmt":"2013-03-06T04:41:47","guid":{"rendered":"http:\/\/invisiblezero.net\/?p=458"},"modified":"2013-03-06T04:41:47","modified_gmt":"2013-03-06T04:41:47","slug":"five-common-php-design-patterns","status":"publish","type":"post","link":"http:\/\/ndthanh.com\/five-common-php-design-patterns\/","title":{"rendered":"Five common PHP design patterns"},"content":{"rendered":"

\"php\"<\/p>\n

Design patterns were introduced to the software community in Design Patterns<\/i>, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (colloquially known as the “gang of four”). The core concept behind design patterns, presented in the introduction, was simple. Over their years of developing software, Gamma et al found certain patterns of solid design emerging, just as architects designing houses and buildings can develop templates for where a bathroom should be located or how a kitchen should be configured. Having those templates, or design patterns<\/i>, means they can design better buildings more quickly. The same applies to software.<\/p>\n

<\/p>\n

Design patterns not only present useful ways for developing robust software faster but also provide a way of encapsulating large ideas in friendly terms. For example, you can say you’re writing a messaging system to provide for loose coupling, or you can say you’re writing an observer<\/i>, which is the name of that pattern.<\/p>\n

It’s difficult to demonstrate the value of patterns using small examples. They often look like overkill because they really come into play in large code bases. This article can’t show huge applications, so you need to think about ways to apply the principles of the example — and not necessarily this exact code — in your larger applications. That’s not to say that you shouldn’t use patterns in small applications. Most good applications start small and become big, so there is no reason not to start with solid coding practices like these.<\/p>\n

Now that you have a sense of what design patterns are and why they’re useful, it’s time to jump into five common patterns for PHP V5.<\/p>\n

<\/a>The factory pattern<\/strong><\/span><\/p>\n

Many of the design patterns in the original Design Patterns<\/i> book encourage loose coupling<\/i>. To understand this concept, it’s easiest to talk about a struggle that many developers go through in large systems. The problem occurs when you change one piece of code and watch as a cascade of breakage happens in other parts of the system — parts you thought were completely unrelated.<\/p>\n

The problem is tight coupling<\/i>. Functions and classes in one part of the system rely too heavily on behaviors and structures in other functions and classes in other parts of the system. You need a set of patterns that lets these classes talk with each other, but you don’t want to tie them together so heavily that they become interlocked.<\/p>\n

In large systems, lots of code relies on a few key classes. Difficulties can arise when you need to change those classes. For example, suppose you have a User<\/code> class that reads from a file. You want to change it to a different class that reads from the database, but all the code references the original class that reads from a file. This is where the factory pattern comes in handy.<\/p>\n

The factory pattern<\/i> is a class that has some methods that create objects for you. Instead of using new<\/code> directly, you use the factory class to create objects. That way, if you want to change the types of objects created, you can change just the factory. All the code that uses the factory changes automatically.<\/p>\n

Listing 1 shows an example of a factory class. The server side of the equation comes in two pieces: the database, and a set of PHP pages that let you add feeds, request the list of feeds, and get the article associated with a particular feed.
\n
<\/a>Listing 1. Factory1.php<\/b><\/p>\n

\ninterface IUser\n{\n  function getName();\n}\n\nclass User implements IUser\n{\n  public function __construct( $id ) { }\n\n  public function getName()\n  {\n    return "Jack";\n  }\n}\n\nclass UserFactory\n{\n  public static function Create( $id )\n  {\n    return new User( $id );\n  }\n}\n\n$uo = UserFactory::Create( 1 );\necho( $uo->getName()."\\n" );\n<\/pre>\n

An interface called IUser<\/code> defines what a user object should do. The implementation of IUser<\/code> is called User<\/code>, and a factory class called UserFactory<\/code> creates IUser<\/code> objects. This relationship is shown as UML in Figure 1.
\n
<\/a>Figure 1. The factory class and its related IUser interface and user class<\/b>
\n\"The
\nIf you run this code on the command line using the php<\/code> interpreter, you get this result:<\/p>\n\n\n\n
\n
% php factory1.php \nJack\n%<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

The test code asks the factory for a User<\/code> object and prints the result of the getName<\/code> method.<\/p>\n

A variation of the factory pattern uses factory methods. These public static methods in the class construct objects of that type. This approach is useful when creating an object of this type is nontrivial. For example, suppose you need to first create the object and then set many attributes. This version of the factory pattern encapsulates that process in a single location so that the complex initialization code isn’t copied and pasted all over the code base.<\/p>\n

Listing 2 shows an example of using factory methods.<\/p>\n

\ninterface IUser\n{\n  function getName();\n}\n\nclass User implements IUser\n{\n  public static function Load( $id )\n  {\n        return new User( $id );\n  }\n\n  public static function Create( )\n  {\n        return new User( null );\n  }\n\n  public function __construct( $id ) { }\n\n  public function getName()\n  {\n    return "Jack";\n  }\n}\n\n$uo = User::Load( 1 );\necho( $uo->getName()."\\n" );\n<\/pre>\n

This code is much simpler. It has only one interface, IUser<\/code>, and one class called User<\/code> that implements the interface. The User<\/code> class has two static methods that create the object. This relationship is shown in UML in Figure 2.
\n<\/a>Figure 2. The IUser interface and the user class with factory methods<\/b>
\n\"The
\nRunning the script on the command line yields the same result as the code in Listing 1, as shown here:<\/p>\n\n\n\n
\n
% php factory2.php \nJack\n%<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

As stated, sometimes such patterns can seem like overkill in small situations. Nevertheless, it’s still good to learn solid coding forms like these for use in any size of project.<\/p>\n

<\/a>The singleton pattern<\/strong><\/span><\/p>\n

Some application resources are exclusive<\/i> in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it’s an overhead to keep opening and closing connections, particularly during a single page fetch.<\/p>\n

The singleton pattern covers this need. An object is a singleton<\/i> if the application can include one and only one of that object at a time. The code in Listing 3 shows a database connection singleton in PHP V5.<\/p>\n

\nrequire_once("DB.php");\n\nclass DatabaseConnection\n{\n  public static function get()\n  {\n    static $db = null;\n    if ( $db == null )\n      $db = new DatabaseConnection();\n    return $db;\n  }\n\n  private $_handle = null;\n\n  private function __construct()\n  {\n    $dsn = 'mysql:\/\/root:password@localhost\/photos';\n    $this->_handle =& DB::Connect( $dsn, array() );\n  }\n\n  public function handle()\n  {\n    return $this->_handle;\n  }\n}\n\nprint( "Handle = ".DatabaseConnection::get()->handle()."\\n" );\nprint( "Handle = ".DatabaseConnection::get()->handle()."\\n" );\n<\/pre>\n

This code shows a single class called DatabaseConnection<\/code>. You can’t create your own DatabaseConnection<\/code> because the constructor is private. But you can get the one and only one DatabaseConnection<\/code> object using the static get<\/code> method. The UML for this code is shown in Figure 3.
\n
<\/a>Figure 3. The database connection singleton<\/b>
\n\"The
\nThe proof in the pudding is that the database handle returned by the handle<\/code> method is the same between two calls. You can see this by running the code on the command line.<\/p>\n\n\n\n
\n
% php singleton.php \nHandle = Object id #3\nHandle = Object id #3\n%<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

The two handles returned are the same object. If you use the database connection singleton across the application, you reuse the same handle everywhere.<\/p>\n

You could use a global variable to store the database handle, but that approach only works for small applications. In larger applications, avoid globals, and go with objects and methods to get access to resources.<\/p>\n

<\/a>The observer pattern<\/strong><\/span><\/p>\n

The observer pattern gives you another way to avoid tight coupling between components. This pattern is simple: One object makes itself observable by adding a method that allows another object, the observer<\/i>, to register itself. When the observable object changes, it sends a message to the registered observers. What those observers do with that information isn’t relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why.<\/p>\n

A simple example is a list of users in a system. The code in Listing 4 shows a user list that sends out a message when users are added. This list is watched by a logging observer that puts out a message when a user is added.
\n
<\/a>Listing 4. Observer.php<\/b><\/p>\n

\ninterface IObserver\n{\n  function onChanged( $sender, $args );\n}\n\ninterface IObservable\n{\n  function addObserver( $observer );\n}\n\nclass UserList implements IObservable\n{\n  private $_observers = array();\n\n  public function addCustomer( $name )\n  {\n    foreach( $this->_observers as $obs )\n      $obs->onChanged( $this, $name );\n  }\n\n  public function addObserver( $observer )\n  {\n    $this->_observers []= $observer;\n  }\n}\n\nclass UserListLogger implements IObserver\n{\n  public function onChanged( $sender, $args )\n  {\n    echo( "'$args' added to user list\\n" );\n  }\n}\n\n$ul = new UserList();\n$ul->addObserver( new UserListLogger() );\n$ul->addCustomer( "Jack" );\n<\/pre>\n

This code defines four elements: two interfaces and two classes. The IObservable<\/code> interface defines an object that can be observed, and the UserList<\/code> implements that interface to register itself as observable. The IObserver<\/code> list defines what it takes to be an observer, and the UserListLogger<\/code> implements that IObserver<\/code> interface. This is shown in the UML in Figure 4.
\n
<\/a>Figure 4. The observable user list and the user list event logger<\/b>
\n\"The
\nIf you run this on the command line, you see this output:<\/p>\n\n\n\n
\n
% php observer.php \n'Jack' added to user list\n%<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

The test code creates a UserList<\/code> and adds the UserListLogger<\/code> observer to it. Then the code adds a customer, and the UserListLogger<\/code> is notified of that change.<\/p>\n

It’s critical to realize that the UserList<\/code> doesn’t know what the logger is going to do. There could be one or more listeners that do other things. For example, you may have an observer that sends a message to the new user, welcoming him to the system. The value of this approach is that the UserList<\/code> is ignorant of all the objects depending on it; it focuses on its job of maintaining the user list and sending out messages when the list changes.<\/p>\n

This pattern isn’t limited to objects in memory. It’s the underpinning of the database-driven message queuing systems used in larger applications.<\/p>\n

<\/a>The chain-of-command pattern<\/strong><\/span><\/p>\n

Building on the loose-coupling theme, the chain-of-command<\/i> pattern routes a message, command, request, or whatever you like through a set of handlers. Each handler decides for itself whether it can handle the request. If it can, the request is handled, and the process stops. You can add or remove handlers from the system without influencing other handlers. Listing 5 shows an example of this pattern.
\n
<\/a>Listing 5. Chain.php<\/b><\/p>\n

\ninterface ICommand\n{\n  function onCommand( $name, $args );\n}\n\nclass CommandChain\n{\n  private $_commands = array();\n\n  public function addCommand( $cmd )\n  {\n    $this->_commands []= $cmd;\n  }\n\n  public function runCommand( $name, $args )\n  {\n    foreach( $this->_commands as $cmd )\n    {\n      if ( $cmd->onCommand( $name, $args ) )\n        return;\n    }\n  }\n}\n\nclass UserCommand implements ICommand\n{\n  public function onCommand( $name, $args )\n  {\n    if ( $name != 'addUser' ) return false;\n    echo( "UserCommand handling 'addUser'\\n" );\n    return true;\n  }\n}\n\nclass MailCommand implements ICommand\n{\n  public function onCommand( $name, $args )\n  {\n    if ( $name != 'mail' ) return false;\n    echo( "MailCommand handling 'mail'\\n" );\n    return true;\n  }\n}\n\n$cc = new CommandChain();\n$cc->addCommand( new UserCommand() );\n$cc->addCommand( new MailCommand() );\n$cc->runCommand( 'addUser', null );\n$cc->runCommand( 'mail', null );\n<\/pre>\n

This code defines a CommandChain<\/code> class that maintains a list of ICommand<\/code> objects. Two classes implement the ICommand<\/code> interface — one that responds to requests for mail and another that responds to adding users. The UML is shows in Figure 5.
\n
<\/a>Figure 5. The command chain and its related commands<\/b>
\n\"The
\nIf you run the script, which contains some test code, you see the following output:<\/p>\n\n\n\n
\n
% php chain.php \nUserCommand handling 'addUser'\nMailCommand handling 'mail'\n%<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n

The code first creates a CommandChain<\/code> object and adds instances of the two command objects to it. It then runs two commands to see who responds to those commands. If the name of the command matches either UserCommand<\/code> or MailCommand<\/code>, the code falls through and nothing happens.<\/p>\n

The chain-of-command pattern can be valuable in creating an extensible architecture for processing requests, which can be applied to many problems.<\/p>\n

<\/a>The strategy pattern<\/strong><\/span><\/p>\n

The last design pattern we will cover is the strategy<\/i> pattern. In this pattern, algorithms are extracted from complex classes so they can be replaced easily. For example, the strategy pattern is an option if you want to change the way pages are ranked in a search engine. Think about a search engine in several parts — one that iterates through the pages, one that ranks each page, and another that orders the results based on the rank. In a complex example, all those parts would be in the same class. Using the strategy pattern, you take the ranking portion and put it into another class so you can change how pages are ranked without interfering with the rest of the search engine code.<\/p>\n

As a simpler example, Listing 6 shows a user list class that provides a method for finding a set of users based on a plug-and-play set of strategies.
\n
<\/a>Listing 6. Strategy.php<\/b><\/p>\n

\ninterface IStrategy\n{\n  function filter( $record );\n}\n\nclass FindAfterStrategy implements IStrategy\n{\n  private $_name;\n\n  public function __construct( $name )\n  {\n    $this->_name = $name;\n  }\n\n  public function filter( $record )\n  {\n    return strcmp( $this->_name, $record ) <= 0;\n  }\n}\n\nclass RandomStrategy implements IStrategy\n{\n  public function filter( $record )\n  {\n    return rand( 0, 1 ) >= 0.5;\n  }\n}\n\nclass UserList\n{\n  private $_list = array();\n\n  public function __construct( $names )\n  {\n    if ( $names != null )\n    {\n      foreach( $names as $name )\n      {\n        $this->_list []= $name;\n      }\n    }\n  }\n\n  public function add( $name )\n  {\n    $this->_list []= $name;\n  }\n\n  public function find( $filter )\n  {\n    $recs = array();\n    foreach( $this->_list as $user )\n    {\n      if ( $filter->filter( $user ) )\n        $recs []= $user;\n    }\n    return $recs;\n  }\n}\n\n$ul = new UserList( array( "Andy", "Jack", "Lori", "Megan" ) );\n$f1 = $ul->find( new FindAfterStrategy( "J" ) );\nprint_r( $f1 );\n\n$f2 = $ul->find( new RandomStrategy() );\nprint_r( $f2 );\n<\/pre>\n

The UML for this code is shown in Figure 6.
\n
<\/a>Figure 6. The user list and the strategies for selecting users<\/b>
\n\"The
\nThe UserList<\/code> class is a wrapper around an array of names. It implements a find<\/code> method that takes one of several strategies for selecting a subset of those names. Those strategies are defined by the IStrategy<\/code> interface, which has two implementations: One chooses users randomly and the other chooses all the names after a specified name. When you run the test code, you get the following output:<\/p>\n

\n strategy.php\nArray\n(\n    [0] => Jack\n    [1] => Lori\n    [2] => Megan\n)\nArray\n(\n    [0] => Andy\n    [1] => Megan\n)\n<\/pre>\n

The test code runs the same user lists against two strategies and shows the results. In the first case, the strategy looks for any name that sorts after J<\/code>, so you get Jack, Lori, and Megan. The second strategy picks names randomly and yields different results every time. In this case, the results are Andy and Megan.<\/p>\n

The strategy pattern is great for complex data-management systems or data-processing systems that need a lot of flexibility in how data is filtered, searched, or processed.<\/p>\n

<\/a>Conclusions<\/p>\n

These are just a few of the most common design patterns used in PHP applications. Many more are demonstrated in the Design Patterns<\/i> book. Don’t be put off by the mystique of architecture. Patterns are great ideas you can use in any programming language and at any skill level.<\/p>\n

<\/a>Resources<\/p>\n

Learn<\/b><\/p>\n