Reputation: 48933
In PHP if I create a singleton method for like 5 different caching classes (memcache, apc, session, file, cookie)
Then I have a main cache class which basicly routes my set() and get() methods to the appropriate caching class. Now lets say I need to use the session, cookie, memcache, and file cache all on the same page. My main cache class would then need to create a new instance 1 time for each of these cache types using a singleton.
SO I would then need to call my singleton methods many times on a page, if I were to set/get 30 different calls to the cache on 1 page, it would call the singleton method that many times.
I am wondering if it is bad practice or not very good to keep calling my singleton over and over on a page?
UPDATE
Below is some code I have started, in it you can get a better example of what I am trying to do... If I were to add something to memcache 40 times on a page, it would call the singleton method for ym memcache class 40 times
/**
* Set a key/value to cache system.
*
* @param string type of cache to store with
* @param string|array keys, or array of values
* @param mixed value (if keys is not an array)
* @return void
*/
public function set($type, $keys, $value = FALSE, $options_arr)
{
if (empty($keys))
return FALSE;
if ( ! is_array($keys))
{
$keys = array($keys => $val);
}
// Pick our Cache system to use
switch ($type) {
case "memcache":
// Cache item to memcache
$this->memcache = Memcache::getInstance();
$this->memcache->get($keys, $value, $options);
break;
case "apc":
// Cache item to APC
$this->apc = APC::getInstance();
$this->apc->get($keys, $value, $options);
break;
case "session":
// Cache item to Sessions
foreach ($keys as $key => $val)
{
// Set the key
$_SESSION[$key] = $val;
}
break;
case "cookie":
// Cache item to Cookie
break;
case "file":
// Cache item to File
break;
}
}
Upvotes: 3
Views: 500
Reputation: 400932
Generally speaking, using singletons is more and more considered as a bad practice (one reason is they make unit-testing harder, if not impossible).
To illustrate that : both symfony and Zend Framework, for their next major version (2.0) are trying to remove as many singletons as they can from both frameworks.
That being said, singletons should be used when it makes sense to have one and only one instance of a given class ; does it make sense in your case ? Up to you to decide ;-)
If you don't want to call your singleton over and over again, you might want to store it in a local variable -- I suppose it might be seen as some kind of (maybe "premature" / "useless") optimization.
For instance, instead if having this kind of code :
Singleton::getInstance()->method();
Singleton::getInstance()->method();
Singleton::getInstance()->method();
You'd have :
$s = Singleton::getInstance();
$s->method();
$s->method();
$s->method();
Not sure how much you'll gain from that, though...
Upvotes: 3