Is it wrong to call the singleton method multiple times on a page in PHP?

In PHP, if I create a singleton method for 5 different caching classes (memcache, apc, session, file, cookie)

Then I have a main cache class that basically routes the set () and get () methods to the corresponding cache class. Now let's say that I need to use the session, cookie, memcache and cache of files on one page. Then my main cache class will need to create a new instance 1 time for each of these types of caching using singleton code.

SO I would then need to repeatedly call my singleton methods on the page, if I were to set / get 30 different calls to the cache on 1 page, it would repeatedly call the singleton method.

I wonder if this is bad practice or is it not good to keep calling my singleton again and again on the page?


UPDATE

Below is the code I started, in it you can get a better example of what I'm trying to do ... If I had to add something to memcache 40 times on the page, it would call the singleton method for ym class memcache 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;
    }

}
+3
source share
1 answer

Generally speaking, the use of singletons is increasingly seen as bad practice (one of the reasons is that they make unit testing more difficult, if not impossible).

: symfony, Zend Framework, (2.0) .


, ; ? ; -)

, - , (, "" / "" ) .

, , :

Singleton::getInstance()->method();
Singleton::getInstance()->method();
Singleton::getInstance()->method();

:

$s = Singleton::getInstance();
$s->method();
$s->method();
$s->method();

, , ...

+3

Source: https://habr.com/ru/post/1729154/


All Articles