PHP
  Home arrow PHP arrow Page 4 - Polymorphism, Design Patterns, and PHP Programming
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PHP

Polymorphism, Design Patterns, and PHP Programming
By: Sams Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 9
    2006-10-05


    Table of Contents:
  • Polymorphism, Design Patterns, and PHP Programming
  • Interfaces and Type Hints
  • The Factory Pattern
  • The Singleton Pattern

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Polymorphism, Design Patterns, and PHP Programming - The Singleton Pattern
    ( Page 4 of 4 )

    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.

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



     
     
    >>> More PHP Articles          >>> More By Sams Publishing
     

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek