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
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)
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();
精彩评论