View Single Post
Old 10-07-2009, 01:57 PM   #5 (permalink)
sketchMedia
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
sketchMedia is on a distinguished road
Default

I think there is a fundamental misunderstanding of this pattern in PHP and its many uses.

A singleton is a class where only one object can created from it, thus making the object of that type a 'singleton' (as its the only one allowed to be created).

This allows you to make sure that only one version of that object is alive at that particular execution, of course it will have to be created again when the next request happens.

In the example given above, the session variable will be over-written on each execution because you don't make the check to see if it already exists, so every request it will be over-written.

Something like this will work:
PHP Code:

class SingletonClassName
{
    private static 
$_pSelf NULL;

    private function 
__construct() {}
    private function 
__clone() {}
    
    public static function 
getInstance()
    {   
        if(!
self::$_pSelf instanceof self)
        {   
            
//is it in the session
            
if(isset($_SESSION['var']) && $_SESSION['var'] instanceof self)
            {   
                return 
self::$_pSelf $_SESSION['var'];
            }

            
//set the self reference
            
self::$_pSelf = new self;

            
//set it up in the session
            
$_SESSION['var'] = self::$_pSelf ;

            
//return the object
            
return self::$_pSelf;
        }   
        return 
self::$_pSelf;
    }   
}

$class SingletonClassName::getInstance(); 
That will now, create a session variable and check on each page view for that object before creating a new one, thus your singleton is now always the same (well until the session expires).

I still don't quite get why you would need this though, most of my singletons are only for that execution and any variables i need saving between page views just go into a namespace'd session via my session wrapper, I very rarely need to save objects to a session because of the way my system works.
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
sketchMedia is offline  
Reply With Quote