Home > Articles > Programming > PHP

This chapter is from the book

This chapter is from the book

4.4 Design Patterns

So, what exactly qualifies a language as being object-oriented (OO)? Some people believe that any language that has objects that encapsulate data and methods can be considered OO. Others would also include polymorphism via inheritance and access modifiers into the definition. The purists would probably list dozens of pages of things they think an OO language must support, such as exceptions, method overloading, reflection, strict typing, and more. You can bet that none of these people would ever agree with each other because of the diversity of OOP languages, each of them good for certain tasks and not quite as good for others.

However, what most people would agree with is that developing OO software is not only about the syntax and the language features but it is a state of mind. Although there are some professionally written programs in functional languages such as C (for example, PHP), people developing in OO languages tend to give the software design more of an emphasis. One reason might be the fact that OO languages tend to contain features that help in the design phase, but the main reason is probably cultural because the OO community has always put a lot of emphasis on good design.

This chapter covers some of the more advanced OO techniques that are possible with PHP, including the implementation of some common design patterns that are easily adapted to PHP.

When designing software, certain programming patterns repeat themselves. Some of these have been addressed by the software design community and have been given accepted general solutions. These repeating problems are called design patterns. The advantage of knowing and using these patterns is not only to save time instead of reinventing the wheel, but also to give developers a common language in software design. You'll often hear software developers say, "Let's use a singleton pattern for this," or "Let's use a factory pattern for that." Due to the importance of these patterns in today's software development, this section covers some of these patterns.

4.4.1 Strategy Pattern

The strategy pattern is typically used when your programmer's algorithm should be interchangeable with different variations of the algorithm. For example, if you have code that creates an image, under certain circumstances, you might want to create JPEGs and under other circumstances, you might want to create GIF files.

The strategy pattern is usually implemented by declaring an abstract base class with an algorithm method, which is then implemented by inheriting concrete classes. At some point in the code, it is decided what concrete strategy is relevant; it would then be instantiated and used wherever relevant.

Our example shows how a download server can use a different file selection strategy according to the web client accessing it. When creating the HTML with the download links, it will create download links to either .tar.gz files or .zip files according to the browser's OS identification. Of course, this means that files need to be available in both formats on the server. For simplicity's sake, assume that if the word "Win" exists in $_SERVER["HTTP_ USER_AGENT"] , we are dealing with a Windows system and want to create .zip links; otherwise, we are dealing with systems that prefer .tar.gz.

In this example, we would have two strategies: the .tar.gz strategy and the .zip strategy, which is reflected as the following strategy hierarchy (see Figure 4.3).

Figure 4.3Figure 4.3 Strategy hierarchy.

The following code snippet should give you an idea of how to use such a strategy pattern:

abstract class FileNamingStrategy {
    abstract function createLinkName($filename);	
}
 
class ZipFileNamingStrategy extends FileNamingStrategy {
    function createLinkName($filename)
    {
        return "http://downloads.foo.bar/$filename.zip";	    
    }	
}
 
class TarGzFileNamingStrategy extends FileNamingStrategy {
    function createLinkName($filename)
    {
        return "http://downloads.foo.bar/$filename.tar.gz";	    
    }	
}
 
if (strstr($_SERVER["HTTP_USER_AGENT"], "Win")) {
    $fileNamingObj = new ZipFileNamingStrategy();
} else {
    $fileNamingObj = new TarGzFileNamingStrategy();
}
 
$calc_filename = $fileNamingObj->createLinkName("Calc101");
$stat_filename = $fileNamingObj->createLinkName("Stat2000");
 
print <<<EOF
<h1>The following is a list of great downloads<</h1>
<br>
<a href="$calc_filename">A great calculator</a><br>
<a href="$stat_filename">The best statistics application</a><br>
<br>
EOF;

Accessing this script from a Windows system gives you the following HTML output:

<h1>The following is a list of great downloads<</h1>
<br>
<a href="http://downloads.foo.bar/Calc101.zip">A great calculator<
a><br>
<a href="http://downloads.foo.bar/Stat2000.zip">The best statistics
application</a><br>
<br> 

TIP

The strategy pattern is often used with the factory pattern, which is described later in this section. The factory pattern selects the correct strategy.

4.4.2 Singleton Pattern

The singleton pattern is probably one of the best-known design patterns. You have probably encountered many situations where you have an object that handles some centralized operation in your application, such as a logger object. In such cases, it is usually preferred for only one such application-wide instance to exist and for all application code to have the ability to access it. Specifically, in a logger object, you would want every place in the application that wants to print something to the log to have access to it, and let the centralized logging mechanism handle the filtering of log messages according to log level settings. For this kind of situation, the singleton pattern exists.

Making your class a singleton class is usually done by implementing a static class method getInstance() , which returns the only single instance of the class. The first time you call this method, it creates an instance, saves it in a private static variable, and returns you the instance. The subsequent times, it just returns you a handle to the already created instance.

Here's an example:

class Logger {
    static function getInstance()
    {
        if (self::$instance == NULL) {
            self::$instance = new Logger();
        }
        return self::$instance;
    }
     private function __construct()
    {
    }
     private function __clone()
    {
 
	        }
     function Log($str)
    {
        // Take care of logging
    }
     static private $instance = NULL;
}
 
Logger::getInstance()->Log("Checkpoint");

The essence of this pattern is Logger::getInstance() , which gives you access to the logging object from anywhere in your application, whether it is from a function, a method, or the global scope.

In this example, the constructor and clone methods are defined as private . This is done so that a developer can't mistakenly create a second instance of the Logger class using the new or clone operators; therefore, getInstance() is the only way to access the singleton class instance.

4.4.3 Factory Pattern

Polymorphism and the use of base class is really the center of OOP. However, at some stage, a concrete instance of the base class's subclasses must be created. This is usually done using the factory pattern. A Factory class has a static method that receives some input and, according to that input, it decides what class instance to create (usually a subclass).

Say that on your web site, different kinds of users can log in. Some are guests, some are regular customers, and others are administrators. In a common scenario, you would have a base class User and have three subclasses: GuestUser , CustomerUser , and AdminUser . Likely User and its subclasses would contain methods to retrieve information about the user (for example, permissions on what they can access on the web site and their personal preferences).

The best way for you to write your web application is to use the base class User as much as possible, so that the code would be generic and that it would be easy to add additional kinds of users when the need arises.

The following example shows a possible implementation for the four User classes, and the UserFactory class that is used to create the correct user object according to the username:

abstract class User {
    function __construct($name)
    {
        $this->name = $name;
    }
     function getName()
    {
        return $this->name;
    }
     // Permission methods
    function hasReadPermission()
    {
        return true;
    }

     function hasModifyPermission()
    {
        return false;
    }
     function hasDeletePermission()
    {
        return false;
    }
     // Customization methods
    function wantsFlashInterface()
    {
        return true;
    }
     protected $name = NULL;
}
 
class GuestUser extends User {
}
 
class CustomerUser extends User {
   function hasModifyPermission()
    {
        return true;
    }
}
 
class AdminUser extends User {
   function hasModifyPermission()
    {
        return true;
    }
     function hasDeletePermission()
    {
        return true;
    }
     function wantsFlashInterface()
    {
        return false;
    }
}
 
class UserFactory {
    private static $users = array("Andi"=>"admin", "Stig"=>"guest",
                           "Derick"=>"customer");
 
    static function Create($name)
    {
        if (!isset(self::$users[$name])) {
            // Error out because the user doesn't exist
        }
        switch (self::$users[$name]) {
            case "guest": return new GuestUser($name);
            case "customer": return new CustomerUser($name);
            case "admin": return new AdminUser($name);
            default: // Error out because the user kind doesn't exist
        }                      
    }
}
 
function boolToStr($b)
{
    if ($b == true) {
        return "Yes\n";
    } else {
        return "No\n";
    }	
}
 
function displayPermissions(User $obj)
{
    print $obj->getName() . "'s permissions:\n";
    print "Read: " . boolToStr($obj->hasReadPermission());
    print "Modify: " . boolToStr($obj->hasModifyPermission());
    print "Delete: " . boolToStr($obj->hasDeletePermission());
 
}
 
function displayRequirements(User $obj)
{
    if ($obj->wantsFlashInterface()) {
        print $obj->getName() . " requires Flash\n";
    }
}
 
$logins = array("Andi", "Stig", "Derick");
 
foreach($logins as $login) {
    displayPermissions(UserFactory::Create($login)); 
    displayRequirements(UserFactory::Create($login));
}

Running this code outputs

Andi's permissions:
Read: Yes
Modify: Yes
Delete: Yes
Stig's permissions:
Read: Yes
Modify: No
Delete: No
Stig requires Flash
Derick's permissions:
Read: Yes
Modify: Yes
Delete: No
Derick requires Flash

This code snippet is a classic example of a factory pattern. You have a class hierarchy (in this case, the User hierarchy), which your code such as displayPermissions() treats identically. The only place where treatment of the classes differ is in the factory itself, which constructs these instances. In this example, the factory checks what kind of user the username belongs to and creates its class accordingly. In real life, instead of saving the user to user-kind mapping in a static array, you would probably save it in a database or a configuration file.

TIP

Besides Create(), you will often find other names used for the factory method, such as factory(), factoryMethod(), or createInstance().

4.4.4 Observer Pattern

PHP applications, usually manipulate data. In many cases, changes to one piece of data can affect many different parts of your application's code. For example, the price of each product item displayed on an e-commerce site in the customer's local currency is affected by the current exchange rate. Now, assume that each product item is represented by a PHP object that most likely originates from a database; the exchange rate itself is most probably being taken from a different source and is not part of the item's database entry. Let's also assume that each such object has a display() method that outputs the HTML relevant to this product.

The observer pattern allows for objects to register on certain events and/or data, and when such an event or change in data occurs, it is automatically notified. In this way, you could develop the product item to be an observer on the currency exchange rate, and before printing out the list of items, you could trigger an event that updates all the registered objects with the correct rate. Doing so gives the objects a chance to update themselves and take the new data into account in their display() method.

Usually, the observer pattern is implemented using an interface called Observer, which the class that is interested in acting as an observer must implement.

For example:

interface Observer {
	function notify($obj);
}

An object that wants to be "observable" usually has a register method that allows the Observer object to register itself. For example, the following might be our exchange rate class:

class ExchangeRate {
    static private $instance = NULL;
    private $observers = array();
    private $exchange_rate;
 
    private function ExchangeRate() {
    }
     static public function getInstance() {
        if (self::$instance == NULL) {
            self::$instance = new ExchangeRate();
        }
        return self::$instance;
    } 
 
    public function getExchangeRate() {
        return $this->$exchange_rate;
    }
     public function setExchangeRate($new_rate) {
        $this->$exchange_rate = $new_rate;
        $this->notifyObservers();
    }
     public function registerObserver($obj) {
        $this->observers[] = $obj;
    }
     function notifyObservers() {
        foreach($this->observers as $obj) {
            $obj->notify($this);
        }
    }
}
 
class ProductItem implements Observer {
    public function __construct() {
        ExchangeRate::getInstance()->registerObserver($this);
    }
     public function notify($obj) {
        if ($obj instanceof ExchangeRate) {
             // Update exchange rate data
             print "Received update!\n";
        }
   }
}
 
$product1 = new ProductItem();
$product2 = new ProductItem();
 
ExchangeRate::getInstance()->setExchangeRate(4.5);

This code prints

Received update!
Received update!

Although the example isn't complete (the ProductItem class doesn't do anything useful), when the last line executes (the setExchangeRate() method), both $product1 and $product2 are notified via their notify() methods with the new exchange rate value, allowing them to recalculate their cost.

This pattern can be used in many cases; specifically in web development, it can be used to create an infrastructure of objects representing data that might be affected by cookies, GET , POST , and other input variables.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020