views:

122

answers:

2

Hi all,

In my team I've been told to write resource class like this style:

class MemcacheService
{
    private static $instance = null;

    private function __construct()
    {

    }

    public static function getInstance($fortest = false)
    {
        if (self::$instance == null)
        {
            self::$instance = new Memcached();

            if ($fortest)
            {
                self::$instance->addServer(MEMTEST_HOST, MEMTEST_PORT);
            }
            else
            {

                self::$instance->addServer(MEM_HOST, MEM_PORT);
            }
        }

        return self::$instance;
    }
}

But I think in PHP resource handles will be released and initialized again every time after a request over. That means MemcacheService::getInstance() is totally equal new Memcached() which cannot be called singleton pattern at all. Please correct me if I'm wrong.

Regards

+1  A: 

No, this is a correct singleton pattern. Everytime you call getInstance(), it will check if self::$instance is null.

if(self::$instance == null)

If it is null, it then creates a new instance of Memcached, which makes self::$instance not null, so the next time it gets called, it will return that same instance.

self::$instance = new Memcached();
Chacha102
But I think it will always be null when start a new request.So <pre><code>if(self::$instance == null)</code></pre> does nothing...
SpawnCxy
Only if you call `MemcacheService::getInstance()` only once within the same php instance.
VolkerK
+1  A: 

You're right that PHP will release most resources (file handles, database connections; but see below) when the script ends. However, if you're accessing the same instance multiple times within a script run, and not passing the reference around, then this is a reasonable way of keeping tabs on "the memcache connection instance", albeit fundamentally equivalent to using a global in the long run.

(* some connections, such as persistent database connections, won't actually be released as such, and the next script to request such a connection could be given a previously opened one back)

Rob