PHP
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Magic Methods> <Object Iteration
Last updated: Tue, 30 Jun 2009

view this page in

Patterns

Patterns are ways to describe best practices and good designs. They show a flexible solution to common programming problems.

Factory

The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Example #1 Parameterized Factory Method

<?php
class Example
{
    
// The parameterized factory method
    
public static function factory($type)
    {
        if (include_once 
'Drivers/' $type '.php') {
            
$classname 'Driver_' $type;
            return new 
$classname;
        } else {
            throw new 
Exception ('Driver not found');
        }
    }
}
?>

Defining this method in a class allows drivers to be loaded on the fly. If the Example class was a database abstraction class, loading a MySQL and SQLite driver could be done as follows:

<?php
// Load a MySQL Driver
$mysql Example::factory('MySQL');

// Load a SQLite Driver
$sqlite Example::factory('SQLite');
?>

Singleton

The Singleton pattern applies to situations in which there needs to be a single instance of a class. The most common example of this is a database connection. Implementing this pattern allows a programmer to make this single instance easily accessible by many other objects.

Example #2 Singleton Function

<?php
class Example
{
    
// Hold an instance of the class
    
private static $instance;
    
    
// A private constructor; prevents direct creation of object
    
private function __construct() 
    {
        echo 
'I am constructed';
    }

    
// The singleton method
    
public static function singleton() 
    {
        if (!isset(
self::$instance)) {
            
$c __CLASS__;
            
self::$instance = new $c;
        }

        return 
self::$instance;
    }
    
    
// Example method
    
public function bark()
    {
        echo 
'Woof!';
    }

    
// Prevent users to clone the instance
    
public function __clone()
    {
        
trigger_error('Clone is not allowed.'E_USER_ERROR);
    }

}

?>

This allows a single instance of the Example class to be retrieved.

<?php
// This would fail because the constructor is private
$test = new Example;

// This will always retrieve a single instance of the class
$test Example::singleton();
$test->bark();

// This will issue an E_USER_ERROR.
$test_clone = clone $test;

?>


Magic Methods> <Object Iteration
Last updated: Tue, 30 Jun 2009
 
add a note add a note User Contributed Notes
Patterns
rskret at gmail dot com
04-Jun-2009 10:46
Ex.2 only makes a 'Singleton' in the sense there is only one object makable.
But! you can still assign the object to other names(like making aliases). Probably not
what you usually want. Change the method a bit and you get only one unique name
for your 'Singleton'.. or else it will bark again and again!
<?php
#if you don't change example 2 you will get a $badDoggie
$badDoggie="I am constructedSorry but I'm already set.Sorry but I'm already set.
            Sorry but I'm already set.Woof!Woof!Woof!"
;
   
// The singleton method
   
public static function singleton()
    {   
        if (!isset(
self::$instance)) {
           
$c = __CLASS__;
           
self::$instance = new $c;
           
#return self::$instance;
       
}
        echo
"Sorry but I'm already set.";
        return
self::$instance; ##...wrong place for this!comment this, uncomment it above
   
}   
?>
<?php
// This would fail because the constructor is private
#$test = new Example;
// This will always retrieve a single instance of the class
$test = Example::singleton();
$again = Example::singleton();
$and_again = Example::singleton();
$test->bark();
$again->bark();
$and_again->bark();
?>
marshall dot mattingly at NOSPAM dot gmail dot com
17-Apr-2009 04:56
Here's my singleton class for php 5.3.0:

<?php
class Singleton {
 
// this must be in every inherited singleton!
 
protected static $_instance;

 
// get the instance
 
final public static function instance() {
   
// create the instance if we don't have one
   
if (empty(static::$_instance)) {
     
$class = get_called_class(); // php 5.3.0
     
static::$_instance = new $class;
    }

    return static::
$_instance;
  }

 
// must protect the constructor
 
protected function __construct() { }

 
// overload __clone
 
final public function __clone() {
    throw new
Exception('Cannot duplicate a singleton.');
  }
}

// a sample extension
class Extension extends Singleton {
 
// has to be here, sadly... if only statics were inherited
 
protected static $_instance;

  protected function
__construct() { ... }

  public function
foo() {
    echo
'foo\n';
  }
}

// example
$extension = Extension::instance();
$extension->foo(); // echo's 'foo\n' as expected
?>

Having to add "protected static $_instance" to every singleton is somewhat annoying. I tried the obvious alternative and stored all the instances within an array in the Singleton class. I ran Extension::getInstance() 1,000,000 over 10 runs to see which method was faster:

Array of $_instances:  3.47s average
Individual $_instance: 1.75s average

Considering the array of instances only had 1 key to search through, it's reasonable to assume that method would get slower as singletons are added, whereas the method above will always stay the same speed. The difference was enough for me to suffer the minor inconvenience.
grummfy at gmail dot com
06-Apr-2009 04:23
Well, for non-php 5.3 users, another way is replacing get_called_class() by get_class(self) ou get_class($this).
grummfy at gmail dot com
06-Apr-2009 03:33
Exemple of singleton that can be used for other class (need phpversion >= 5.3)
<?php
class SingletonModel
{
   
/**
     * Instance of singleton's class
     *
     * @var array
     */
   
private static $_instance;

   
/**
     * All constructeur should be protected
     */
   
protected function __construct(){}

   
/**
     * Singleton method to load a new object
     *
     * @return HlPwd_SingletonModel
     */
   
public static function singleton()
    {
        if (!isset(
self::$instance[ get_called_class() ]))
        {
           
$c = get_called_class();
           
self::$instance = new $c;
        }
       
        return
self::$instance;
    }

   
/**
     * Destroy the singleton
     */
   
public function destroySingleton()
    {
        unset(
self::$_instance[ get_class($this) ]);
    }

   
/**
     * Destructeur
     */
   
public function __destruct()
    {
        unset(
self::$_instance);
    }

   
/**
     * Impeach the clone of singleton
     */
   
public function __clone()
    {
       
trigger_error('Cloning not allowed on a singleton object', E_USER_ERROR);
    }
}

# EOF

you can easyli use it  like that

class mySingChild extends SingletonModel
{
    protected function
__construct()
    {
       
//do important things
   
}

    public function
foo()
    {
        echo
'hello world';
    }
}

$t = mySingChild::singleton();
$t->foo();
Talraith
12-Mar-2009 04:42
Building on vaddsm(at)gmail.com's idea...

I think a simpler option is to have a loader class/object and then the actual class.  It keeps your class more secure in that you are defining the visibility on $instances and you keep your class neat and tidy.

I found this useful when trying to use the singleton method on a class that extends another class.

<?php

class module_loader {
    private static
$instances;

    public static function
getInstance($module_name) {
        if (!isset(
self::$instances[$module_name])) {
           
self::$instances[$module_name] = new $module_name();
        }

        return
self::$instances[$module_name];
    }
}

class
module_base {
   
proteced $name;

    public function
__construct() {
       
// Do initialization stuff here

   
}

    public final function
SomePermanentFunction() {
       
// Perform function actions
   
}
}

class
module_test extends module_base {
    public
$my_var;

    public function
__construct() {
       
parent::__construct();

       
$this->name = 'test';
       
$this->my_var = '';
    }

    public function
ModuleSpecificFunction() {

    }
}

?>

So then once you have all of that defined, you can then use it like such:

<?php

// Get first instance and set value
$instance1 = module_loader::getInstance('module_test');
$instance1->my_var = 'abc';

print
"Instance 1 Var = " . $instance1->my_var;

// Create second instance and check value
$instance2 = module_loader::getInstance('module_test');

print
"Instance 2 Var = " . $instance2->my_var;

// Set value on second instance, check first instance
$instance2->my_var = 'def';

print
"Instance 1 Var = " . $instance1->my_var;

?>

The output would then look like this:

Instance 1 Var = abc
Instance 2 Var = abc
Instance 1 Var = def

Thus $instance1 and $instance2 are created using the factory pattern but they both point back to the same object (singleton pattern).
vaddsm(at)gmail.com
22-Jan-2009 08:34
Hello! I want to suggest another fast and universal way to create a singleton, that can store instances any class types. The idea based on php's ability to create object's properties in run time, and magic functions support. Main trick is to create not existed property in __get method and assign to it a value of new instance of class, named as property.

Code:

<?php

class fClassOne
{

 public function
get()
 {
  return
"value 1<br>\n";
 }

 public function 
__construct()
 {
  echo
"fClassOne constructed<br>\n";
 }

}

class
fClassTwo
{

 public function
get()
 {
  return
"value 2<br>\n";
 }

 public function 
__construct()
 {
  echo
"fClassTwo constructed<br>\n";
 }

}

class
fSingleton
{
 public function
__get($sClassName)
 {
  echo
"isset check<br>\n";
  if(!isset(
$this->{$sClassName})) $this->{$sClassName} = new $sClassName;
  return
$this->{$sClassName};
 }
}

$MySingleton = new fSingleton();

for (
$i = 0; $i < 5; $i++) echo $MySingleton->fClassOne->get();

echo
$MySingleton->fClassTwo->get();
echo
$MySingleton->fClassTwo->get();

 
?>

Output:

isset check
fClassOne constructed
value 1
value 1
value 1
value 1
value 1
isset check
fClassTwo constructed
value 2
value 2
Anonymous
31-Dec-2008 07:34
nbcarts:

1: The singleton pattern ensures that only one instance of a class is ever created. Thus, applying it to a database connection object is common, since reusing a connection reduces latency and slows down reaching the database server's connection limit. If a database connection is only made in the singleton's constructor then it is probably impossible to accidentally open another connection via that object.

I say "probably impossible" because there are still some other issues: in this example, an invalid database connection identifier can be stored, retrieved, or lost (since it is an unserializable resource type) via object serialization without careful attention to the __sleep and __wakeup magic methods (and probably won't be valid on deserialization even if it is retained), and the __clone magic method should be implemented in a way that prevents object duplication.

(This example also ignores database connection pooling to stay focused on singletons.)

2: A singleton does not contain itself; it contains a reference to itself, which is conceptually similar to a pointer from the C language or a reference from Java. (In fact these are all very different under the hood and in practice, but I will ignore this for simplicity.)

Consider the following typical PHP 5.0 to 5.2 implementation:

<?php
class Example {
   
    private static
$instance;
   
    private
__construct() {
       
// Do important initializations here, like normal.
   
}
   
    public static function
getInstance() {
        if (
null == self::$instance):
           
// First invocation only.
           
$className = __CLASS__;
           
self::$instance = new $className();
        endif;
        return
self::$instance;
    }
   
    public function
__clone() {
        throw new
Exception('Illegally attempted to clone ' . __CLASS__);
    }
}
?>

Static class member variables can exist even without an instance of their class, and static class methods can be invoked without a class instance as well. The member variable that holds a reference to the singleton class instance ($instance) is static, as is the method to instantiate a singleton object (Example::getInstance()). Note that the variable $instance is private, so it cannot be affected by anything external to the class (thus preventing outside code from creating an instance of Example).

Static member variables are not really "inside" a class; each class instance points to the same static member variables as other instances, "sharing" these static variables between them (in a way) even before any class instances exist. Thus, Example::getInstance() always checks the same $instance variable.

3: The constructor has an access specifier of "private" to prevent direct instantiation using the "new" operator. (Prior to the implementation of the __callStatic features of PHP 5.3 it is not useful to mark the constructor "protected" since subclasses won't automatically also be singletons.) However, private methods can be invoked from a class's other methods; the static method Example::getInstance() is therefore allowed to invoke the private constructor. On first invocation, it creates an instance of Example and stores a reference to it in $instance. Subsequently, it just returns this reference.

4: The singleton pattern makes a class (slightly) more complicated, and the overhead of invoking its instantiation method is probably slightly higher than accessing a global variable instead. However, the benefits are substantial from an architectural perspective: it helps prevent performance losses due to accidentally instantiating more than one heavyweight class, it helps prevent bugs due to accidentally instantiating more than one instance of a class (such as a class that renders the requested HTML document in an online content management system), and helps keeps your global namespace and other lexical scopes clean even prior to the introduction of proper namespaces in PHP 5.3 (thus helping to prevent accidental variable clobbering or unexpected initial variable values from a previous module).
k at tamayuz dot com
13-Oct-2008 08:59
Till now writing singleton classes depends on making class constructor private or protected and that sounds good, but what if class constructor must be public (for example, a singleton class inherits from a non-singleton class which already has a public constructor). The way to do so is:

<?php
   
class nonSingleton
   
{
        protected
$_foo;
       
        public function
__construct($foo)
        {
           
$this -> _foo = $foo;
        }
    }
   
    class
Singleton extends nonSingleton
   
{
       
/**
         * Single instance of the class
         *
         * @var Singleton
         */
       
protected static $_instance = NULL;
       
/**
         * A flag to know if we are in getInstance method or not.
         *
         * @var bool
         */
       
protected static $_withinGetInstance = false;
       
       
/**
         * Public singleton class constructor
         *
         * @param mixed $foo
         */
       
public function __construct($foo)
        {
            if (!
self :: $_withinGetInstance)
                throw new
Exception('You cannot make a new instance of this class by using constructor, use getInstance() instead...');
           
parent :: __construct($foo);
           
/*
                Any other operations constructor should do...
            */
       
}
       
       
/**
         * Regular getInstance method
         *
         * @param mixed $foo
         * @return Singleton
         */
       
public static function getInstance($foo)
        {
           
self :: $_withinGetInstance = true;
            if (!
self :: $_instance)
               
self :: $_instance = new Singleton($foo);
           
self :: $_withinGetInstance = false;
            return
self :: $_instance;
        }
    }
?>
Anonymous
06-Oct-2008 09:38
The "red-neck singleton" presented by wbcarts is not a singleton, but a presentation of static class members.

Static members are shared by every instance of that class, and as such should work precisely as he describes using them.

Singleton pattern is used to ensure that there only ever exists one instance of the singleton class.
wbcarts at juno dot com
03-Oct-2008 09:49
"Red-Necked" SINGLETON STYLE

I'm not sure if this is a so-called "pattern" because I'm only using plain ol' static data - nuttin fancier than that. It seems to fit the singleton pattern you guys have been describing, but without private constructors, or references to itself. Here's my singleton class... after it's been country-fried!

<?php

class MutableSingletonModel {
  public static
$data1 = 1;
  public static
$data2 = 1;

  public static function
getInstance() {
    return new
MutableSingletonModel();
  }

  public function
getData1() {
    return
self::$data1;
  }

  public function
getData2() {
    return
self::$data2;
  }

  public function
setData1($value) {
    if(
$value > 0 && $value < 100) self::$data1 = $value;
  }

  public function
setData2($value) {
    if(
$value > 0 && $value < 100) self::$data2 = $value;
  }

  public function
__toString() {
    return
'MutableSingletonModel[data1=' . self::$data1 . ', data2=' . self::$data2 . ']';
  }
}

// try to set data before any objects is created
MutableSingletonModel::$data1 = 55;

$msm1 = MutableSingletonModel::getInstance();  // use the getInstance() method
$msm2 = new MutableSingletonModel();           // use the default constructor
$msm2->setData2(78);                           // set data with an instantiated object

echo $msm1 . '<br>';
echo
$msm2 . '<br>';
echo
MutableSingletonModel::getInstance() . '<br>';
echo (new
MutableSingletonModel());
?>
Each echo above writes: MutableSingletonModel[data1=55, data2=78]

... Now, I had a really hard time to crack the mystery of the private constructor. To me, any "data", "object", or "thing", of which there is only one, doesn't require "no way to construct it". Furthermore, how can an object (of which there is only one), contain another object of itself inside? Next time I buy a new Cadillac, I'm definitely gonna check the trunk for another!
Anonymous
30-Sep-2008 12:44
Let me describe another pattern it is called “Decorator”. It can be used to add features to already written object. It is useful for extending some library classes from your framework without changing the original classes (especially if somebody else wrote those). The actual meaning is best presented in an example.

<?php
// the main interface in which we going to do some decoration
interface salad{
    public function
wait();
}

// main class which is already defined and you can't or don't want to change
class shopSalad implements salad{
    private
$tomatoes;
    private
$cucumbers;
    private
$cheese;
   
    public function
__construct($tomatoes, $cucumbers, $cheese){
       
$this->tomatoes = $tomatoes;
       
$this->cucumbers = $cucumbers;
       
$this->cheese = $cheese;
    }
   
    public function
wait(){
        echo
"the salad is served using {$this->tomatoes} tomatoes, {$this->cucumbers} cucumbers and {$this->cheese} gr. of cheese.";
    }
}

// abstract decorator class - note that it implements salad
abstract class saladDecorator implements salad{
    protected
$salad// the object for decoration
   
public function __construct(salad $salad){
       
$this->salad=$salad;
    }
   
// there is no need to mention the wait function therefore this class inherits the original salad
    // the purpose of this class is maintaining the type of the object produced by the decorators.
    // it inherits the same interface as the original and it will be inherited by the concrete decorators
}

// sauce decorator
class saladSauce extends saladDecorator {
    public function
wait(){
       
$this->salad->wait();
        echo
" Then it was decorated with some sauce.";
       
    }
}

// onions decorator
class saladOnions extends saladDecorator {
    public function
wait(){
       
$this->salad->wait();
        echo
" Then it was decorated with some onions.";
    }
}

$order1 = new shopSalad(2,1,100); // creates the salad in the normal way
$order1 = new saladSauce($order1); // add a decorator to the class
$order1->wait();
echo
'<br />';

// or
$order3 = new saladOnions(new saladSauce(new shopSalad(1,0.5,50))); // you don't need to load a variable with the reference
$order3->wait();
?>

this will outputs:
the salad is served using 2 tomatoes, 1 cucumbers and 100 gr. of cheese. Then it was decorated with some sauce.
the salad is served using 3 tomatoes, 2 cucumbers and 100 gr. of cheese. Then it was decorated with some onions. Then it was decorated with some sauce.
the salad is served using 1 tomatoes, 0.5 cucumbers and 50 gr. of cheese. Then it was decorated with some souse. Then it was decorated with some onions.

The pattern is not intended to be used with simple object and I couldn't do more simple than that. The pattern is useful in every way when the extending of an object is required. It can be used to divide some methods from others or to create layers of interaction with the object. In example if you have an file interface and a imageFile class which implements the file and then you can have also an textFile for the textFile you can do some layering and if you want to read the file as XML you can mace a decorator to do so. The XML decorator will inherit the interface file so you can save it and    the instance of textFile will be given to create the decorator so you can read the actual text and pars it as XML. It is possible the file to be .ini or some other text based document and you can make a decorator for every one of them. This is the actual benefit of the pattern.
Partty
29-Sep-2008 11:13
The singleton effect you are applying to can be achieved in a old-fashioned and simpler way. Remember that the 'static' is the way for sharing the data between the objects from one type. And there is no pattern in this. So the only think you can do is to use the static keyword. If your program is already written and the rewrite is not recommended there is the "adapter pattern" witch can be used. It is intended to adapt an object to an already build environment. This is one way to have singleton functionality without actually the singleton pattern, it uses a class with static data and static methods and a adaptor class to adapt those methods to your interface.

The example shows how the every instance of the singlePoint class givs you the same data.
<?php
class single {
   
    static
$a;
    static
$b;
   
    protected static function
_start($a,$b){
       
self::$a=$a;
       
self::$b=$b;
    }
    protected static function
_get_a(){
        return
self::$a;
    }
    protected static function
_get_b(){
        return
self::$b;
    }
}
class
singlePoint extends single {
    public function
__construct($a='',$b=''){
        if(
$a!='' && $b!=''){
           
single::_start($a,$b);
        }
    }
    public function
get_a(){
        return
single::_get_a();
    }
    public function
get_b(){
        return
single::_get_b();
    }
}

class
scopeTest{
    public function
__construct(){
       
$singlePointInstance = new singlePoint();
        echo
'In scopeTest a='.$singlePointInstance->get_a().'<br />';
    }
}

$theSingle = new singlePoint(3,5);
echo
'In index a='.$theSingle->get_a().'<br />';

$theScopeTest = new scopeTest();
?>

My point is that you don't need single instance of the class but you need access to the same data over and over again ant the build in way to do that in every language I know so far is the 'static' keyword. It was engineered to give you this functionality. All the singleton patterns and even this adapter is unnecessary complication of the structure. KISS = “Keep It Simple Stupid” no need of that!
uacaman at gmail dot com
23-Sep-2008 06:47
In response to Partty:

Singleton is a very useful pattern, i guess you a missing the point.

Singleton is usefull to share a single instance of a class, lets say a config class among your application without strong coupling and thus making the code more easy to give maintenance in case of changes. Guess this is the whole point of OO.

Uacaman
Partty
20-Sep-2008 03:58
The singleton pattern is not verry userful. you can easely work around the problem in so many ways but it is not wort it.
When building an complex application you first have to desin a layer structure and if you do that well you do not need a singleton in any way.

btw the simplest way is to not use a instance of the class but only static methods and variables. there is no lost functionality and if you need this complexation so badly it's a good and fast solution.

<?php
class stat {
  public static
$any_data;

  private function
__construct(){} //locking the construction method

 
public static function func1($arg1){
   
self::$any_data=$arg1; // or more genius code
 
}
}

// the calling
stat::func1('Big data string to be writen in $any_data');
echo
stat::$any_data; //prints the string
?>

It is goot to point out that this is more error free way to do it, since you have the class name "stat" or the "self" word and then the var as it is deklared '$any_data' no dolar sign shifting.

and hear a more simple solution of the singleton problem: $GLOBALS['db']= new mysql();
and then use the object everywhere without woring for creating other instances. :) You benefin from the object's security and so on... and from the globality of the GLOBALS if the globals are forbiden you can use the $_SESSION instead, but remember that the objects aper ok in the session on the execution of the script the first time but the data will not be userful when you try to extract it from the session the second time you executing the script, unles you take some mesurs.
Mattlock
07-Sep-2008 01:49
I've been forward-developing for PHP 5.3, and couldn't help but notice that late-static-binding makes implementing Singletons simple. Its even easy to set up some function forwarding so that static calls are transformed into non-staic calls:

<?php
// Requires PHP 5.3!
class Singleton {
    public static function
Instance() {
        static
$instances = array();
       
$class = get_called_class();
        if (!
array_key_exists($class, $instances)) {
           
$instances[$class] = new $class();
        }
        return
$instances[$class];
    }
    public static function
__callStatic($func, $args) {
       
$class = static::Instance();
        return
call_user_func_array(array($class, '__'.$func), $args);
    }
}

class
Earth extends Singleton {
    public function
__DoSomething($a, $b) {
        return
15 + $this->SomethingElse($a, $b);
    }
    protected function
SomethingElse($c, $d) {
        return
$c % $d;
    }
}

echo
Earth::DoSomething(6,27);
?>
alexander gavazov
27-Aug-2008 02:05
For quick instance access use function
<?php
class Example{....}

function
Example {
  return
Example::getInstance();
}

// Global access
Example()->sayHallo(...);
Example()->doSomething(...);
print
Example()->someData;
?>
shenkong at php dot net
14-Aug-2008 02:44
Strategy:

<?php
interface FlyBehavior {
    public function
fly();
}
interface
QuackBehavior {
    public function
quack();
}
class
FlyWithWings implements FlyBehavior {
    public function
fly() {
        echo
"I'm flying!!\n";
    }
}
class
FlyNoWay implements FlyBehavior {
    public function
fly() {
        echo
"I can't fly!\n";
    }
}
class
FlyRocketPowered implements FlyBehavior {
    public function
fly() {
        echo
"I'm flying with a rocket!\n";
    }
}
class
Qquack implements QuackBehavior {
    public function
quack() {
        echo
"Quack\n";
    }
}
class
Squeak implements QuackBehavior {
    public function
quack() {
        echo
"Squeak\n";
    }
}
class
MuteQuack implements QuackBehavior {
    public function
quack() {
        echo
"<< Silence >>\n";
    }
}
abstract class
Duck {
    protected
$quack_obj;
    protected
$fly_obj;
    public abstract function
display();

    public function
performQuack() {
       
$this->quack_obj->quack();
    }
    public function
performFly() {
       
$this->fly_obj->fly();
    }
    public function
swim() {
        echo
"All ducks float, even decoys!\n";
    }
    public function
setFlyBehavior(FlyBehavior $fb) {
       
$this->fly_obj = $fb;
    }
    public function
setQuackBehavior(QuackBehavior $qb) {
       
$this->quack_obj = $qb;
    }
}

class
ModelDuck extends Duck {
    public function
__construct() {
       
$this->fly_obj = new FlyNoWay();
       
$this->quack_obj = new MuteQuack();
    }
    public function
display() {
        echo
"I'm a model duck!\n";
    }
}
$model = new ModelDuck();
$model->performFly();
$model->performQuack();
$model->setFlyBehavior(new FlyRocketPowered());
$model->setQuackBehavior(new Squeak());
$model->performFly();
$model->performQuack();
?>
Anonymous
12-Aug-2008 12:48
Apologies to tedmasterweb, since I was incorrect in my note just prior. His sanitizing method would work, since it is based on known values from a switch statement. I had read it too quickly as the more common method of simply appending ".php" to variable values used in include directives in order to ensure that included files are PHP files, like so in a common __autoload variety often seen in the wild:

<?php
function __autoload($class) {
    require_once(
"path/to/classes/$class.php");
}
?>

This was the sort of unsafe usage of the include directives I was commenting on.
Anonymous
12-Aug-2008 12:41
Tedmasterweb's point is a good one, though sanitizing inputs is often even more subtle than you would expect. For instance, his sanitizing solution would fail if the supplied driver name were "../../../../../../../../etc/passwd\0" (which, as you'll note, is null-byte-terminated). The underlying C-functions that run most modern POSIX-compliant and POSIX-based operating system filesystem operations will treat the ASCII null byte as a string termination character, and so will ignore the ".php" he appended to the path. Thus, this attack would still succeed. This attack is described in further detail here (the link is too long for the word wrapping, but it will still work):

http://us3.php.net/manual/en/security.filesystem.php
#security.filesystem.nullbytes

In my own __autoload functions, I tend to provide a validating regex for class or interface names to only allow characters I know are safe (though this code might have to be adjusted once namespace support is fully functional in PHP). For anyone who prefers to attempt to remove unsafe characters instead, I suggest the following list at a minimum:

period (for the ".." pseudo-directory), slash and backslash (for directory separators; both work on Windows systems), the explicit DIRECTORY_SEPARATOR constant, and the ASCII null byte (which can be typed in code as "\0").

Usage of the PHP functions escshellcmd or escshellarg might also be advisable, depending on how your code is written (particularly depending on whether it is executing a shell command or including a file).
tedmasterweb at gmail dot com
26-Jun-2008 07:21
Regarding Example #1:

Be sure to "sanitize" your variables before using them for including files.

Example #1 assumes the variable $type contains sanitized data (and NOT something threatening like '../../../../../etc/passwd').

One approach might be as follows:

<?php
switch ( $type ) {
    case
"MySQL":
       
$type = 'mysql';
        break;
    case
"SQLite":
       
$type = 'sqlite';
        break;
    default:
        throw new
Exception ('Driver not found');
}

if (include_once
'Drivers/' . $type . '.php') {
   
$classname = 'Driver_' . $type;
    return new
$classname;
} else {
    throw new
Exception ('Driver not found');
}

?>

Naturally, the examples are brief and intended to express the issue at hand, not input sanitizing methods, but someone might find this note helpful.

HTH
Alex (raffe) toader_alexandru at yahoo dot com
03-Jun-2008 06:04
Db layer design algorithm:
"Separation of database layer by database functionality"

First we draw this line:

Application
-------------
     DB

Here comes the new thing:
The db layer we separate it into two areas like this:

Db layer
       |
select | insert, update delete
       |

in the left side we have the select part.
The difference between the left and the right sides is that select side has no connection with the db structure - you can take data querying all table, while the right side is table oriented.

Select side:
Here all queries are in one file called "getters". Like getterUsers.

Inside it will be the body of the query but the fields that are to be selected will be build dynamically.
When calling this "getter" you will provide an array of fields to be selected or no fields, situation when it will take all fields.

To keep those db field names as low as possible in this architecture - so the above code dont need to know about the name of the fields in db, you will make just above this "getter", a "filter" file.
This filter will have a switch with a key and inside will call the getter with fields from db.
Ex:
<?php
switch(key)
case
'Label':
$fields = array("label", "firstName");
$obj->getUser($fields)
break;
?>

Above this filter you will have a "caller" that will call the "filter" with the key:
Ex:
<?php
function callerUserLabel()
{
->
filterUserLabel('Label');
}
?>

So in the higher code you just make
->callerUserLabel();
and this will return all what you need.

If you want this query to get out of the db and another field called "email", you just create another case in the switch and a "caller" to call that case.

Dynamic and extensible.

----------------

Now on the insert update side.
Here we only think in db tables.

First we do some "checkers" for all fields in db.
checkerTableName.php
This will contain an array with all the fields and the checks that must be done on that field and perform the checks only on the provided fields.

Then we do the "updaters". Those are build dinamically like the "getters" - if fields provided, only those updated. If all fields provided, can be used as an "inserter".

When performing an insert, all checks on that table will be done.

When performing an update on only one field - like updating a label, only that label will be checked to be in conformity with requirements like a length, special chars inside.
Dependency checks are made here also.

When having in one application action a multiple insert or update (when inserting an operator also add a webUser lets say) you do above those "inserter" and "updater" files a small "manager" that will do:
->checkOperatorFields();
->checkWebUserFields();

->insertOperator();
->insertWebUser();

If no error is thrown, all things will go nice and quiet.

Now also the "getters" will have their fields checked when needed using those checkers. I am talking about the values that are given as parameters not about the ones that are returned from db.

If you are working with domain objects or business logic objects (whatever you call them) above the db layer you will have to make below that line we first draw a "business logic asambler" object that will make from your data what you want.

If this dont exist, at least an intermediary layer that will map the names from db with the ones used in application must be done in both directions - from application to db and from db to application.

-------------------------------------

Advantages of this architecture:
- Usefull in complex application especheally where the selects are made ussually from many tables so you dont have to load lots and lots of files and to get lost in the logic for one simple select.
- NO DUPLICATE CODE
- Simple and intuitive.
- Flexible and expendable.

-----------
"A place where this idea is exposed completely or to debate on it:"

http://www.kurzweilai.net/mindx/show_thread.php?rootID=122913
Andrea Giammarchi
01-Jun-2008 05:49
A tricky way to implement Factory or Singleton is this one:
<?php

class A {
   
// your amazing stuff
}

// implicit factory
function A( /* one or more args */ ){
    return new
A( /* one or more args */ );
}

$a = A(1,2,3);
$b = A(2,3);

// or implicit Singleton
function A( /* one or more args */ ){
    static
$instance;
    return isset(
$instance) ? $instance : ($instance = new A( /* one or more args */ ));
}

A(1,2,3) === A(2,3); // true
?>

More details in WebReflection, byez
krisdover at hotmail dot com
21-May-2008 03:43
The Singleton pattern shown in the above example can still be broken by object serialization. e.g.

<?
class SingleFoo{
  private static
$instance;
  public
$identity = "in the end, there can be only one foo\n";

  private function
__construct() {}

  public static function
getInstance(){
      if(!
self::$instance){
         
self::$instance = new SingleFoo();
      }
      return
self::$instance;
  }

  public function
setIdentity($identity){
    
$this->identity = $identity;
  }

  public function
getIdentity(){
     return
$this->identity;
  }
}

$foo = unserialize( serialize(SingleFoo::getInstance()) );
$foo->setIdentity("new foo on the block\n");

print(
SingleFoo::getInstance()->getIdentity());
print(
$foo->getIdentity());

// result:
// in the end, there can be only one foo
// new foo on the block
?>

A possible solution to this problem involves using the magic method __wakeup() in the Singleton class to enforce the Singleton pattern during unserialization:

<?
class Singleton{
   
// ....

   
public function __wakeup(){
       if(!
self::$instance){
         
self::$instance = $this;
       }else{
         
trigger_error("Unserializing this instance while another exists voilates the Singleton pattern",
             
E_USER_ERROR);
       }
  }

 
// ....
}
?>

The unserialization would be permitted if it does not result in additional instances of the Singleton, and instances restored in this way would still be accessible via the Singleton static factory method.

Kris Dover
shane dot harter at midwayproducts dot com
13-May-2008 07:00
Re: Chris

Question re:  // Mangle the arguments into an array

Why not just use func_get_args() ? Am I missing something?

I mean, (no offense) but generally speaking I'm not a fan of what you put together.

I can see the benefit of abstracting the plumbing needed for a singleton in a common base class.

So I understand your thinking.

But I disagree with it. IMO creating a class hierarchy is about properly modeling a system (in the case of an event model) or an entity (in the case of a data model).

So instead of using inheritance to better solve a problem domain, I'm using it to handle an implementation detail.

IMO, creating an ISingleton interface to enforce continuity, and a code template of an empty class w/ all the required singleton programming would be much better.
someone at somewhere dot com
05-May-2008 08:20
If you want a singleton and you don't mind on throwing a stop error/exception when a 2nd instace is created instead of returning the already created object, then this code works with subclassing and without getInstace alike functions (just with __construct)

<?php

class SINGLETON
{
   
// the array for checking the created instances
   
protected static $singletons = array ();

   
// make it final so extended classes cannot override it
   
final public function __construct ()
    {
       
$classname = get_class ( $this );

        if ( ! isset (
self::$singletons[$classname] ) )
           
// instead of $this it could be any value since we are checking for isset, but a reference to the object may be useful in a possible improvement, somewhat
           
self::$singletons[$classname] = $this;
        else
           
// your favorite stop error here
           
trow new Exception ();
    }

   
// final as well, no overriding, plus protected so it cannot be called
   
final protected function __clone () {}
}

class
X extends SINGLETON
{
   
//...
}

class
Y extends X
{
   
//...
}

$x = new X ();
$y = new Y ();

$a = new X (); // execution stops, as an instance of X is created already

$b = new Y (); // execution stops, as an instance of Y is created already, it DOES NOT give problems with X, despite extending X

?>

so, if it is ok to stops the execution, this method is way simpler

it must stops the execution because no matter what, __construct will return a reference to the new object, always, so if the script goes on further you will have effectively 2 instances (as a matter of fact, the code above only checks the existence of another object from the same class, it does not prohibit the creation of a new one)

hth
Chris
18-Apr-2008 04:07
I cannot belive I was so stupid with my first note on this...

As any Singleton class forces a design pattern on to the user, and is really just a helper class for that design pattern, there is no reason not to force them to mangle any arguments into an array, which allows me to get rid of the use of the ReflectionClass and allows protected constructors.

If someone can delete the first note to hide my shame that would be great, and this bit of this one upto the ----- marker below :D

To save people the trouble of finding my previous note:

-----

This is a Singleton helper class inspired by Mattlock's Singleton class with interface.

It has the advantages of:

1) It uses only a single abstract class instead of an interface and class definition.
2) It allows for multiple instances of classes where you only wish to have one of any instance initialised with certain arguments such as connections to different databases, they may use the same class, but there will be one instance for each database.

This method should allow multiple child classes to extend the Singleton class, and only requires a small about of argument mangling to make it work.

<?php

abstract class Singleton
{
    static abstract public function
getInstance();

    static final protected function
getClassInstance($klass, $args=NULL)
    {
       
// Initialize array for $instances
       
if(self::$instances === NULL)
           
self::$instances = array();

       
// Initialize array for instances of $klass
       
if(!array_key_exists($klass, self::$instances))
           
self::$instances[$klass] = array();

       
// Create key from args
       
$key = serialize($args);

       
// Instantiate $klass
       
if(!array_key_exists($key, self::$instances[$klass]))
        {
               
self::$instances[$klass][$key] = new $klass($args);
        }

       
// Return instance of $klass
       
return self::$instances[$klass][$key];
    }

    static private
       
// Storage for all instances of Singleton classes
       
$instances;
}

final class
MySingleton extends Singleton
{
    static public function
getInstance()
    {
        return
Singleton::getClassInstance(__CLASS__);
    }

   
// Construct should be protected.
   
protected function __construct() {}
}

final class
NamedSingleton extends Singleton
{
    public
       
$name;

   
// Default arguments here NOT constuctor to prevent dupilicate instances.
   
static public function getInstance($name = 'Default')
    {
       
// Mangle the arguments into an array
       
$args = array('name' => $name);
        return
Singleton::getClassInstance(__CLASS__, $args);
    }

   
// Constructor must accept a single array containing all the arguments, if it wants to get any.
   
protected function __construct($args)
    {
       
$this->name = $args['name'];
    }
}

echo
'<pre>';

$a = MySingleton::getInstance();
$b = MySingleton::getInstance();
var_dump