Ejemplo n.º 1
0
 /**
  * Init.
  * @param  string     $name
  * @param  array|null $options
  * @return Froq\Cache\Agent\AgentInterface
  */
 public static final function init(string $name, array $options = null) : AgentInterface
 {
     // default = true
     $once = (bool) ($options['once'] ?? true);
     if ($once && isset(self::$agents[$name])) {
         return self::$agents[$name];
     }
     $agent = null;
     switch (strtolower($name)) {
         case self::AGENT_FILE:
             $agent = new File();
             break;
         case self::AGENT_APCU:
             $agent = new Apcu();
             break;
         case self::AGENT_REDIS:
             $agent = new Redis();
             break;
         case self::AGENT_MEMCACHED:
             $agent = new Memcached();
             break;
         default:
             throw new CacheException("Unimplemented agent name '{$name}' given!");
     }
     // set ttl if provided
     isset($options['ttl']) && $agent->setTtl($options['ttl']);
     // set host/port if provided (redis, memcached)
     if (isset($options['host']) && method_exists($agent, 'setHost')) {
         $agent->setHost($options['host']);
     }
     if (isset($options['port']) && method_exists($agent, 'setPort')) {
         $agent->setPort($options['port']);
     }
     // set dir (file)
     if (isset($options['dir']) && method_exists($agent, 'setDir')) {
         $agent->setDir($options['dir']);
     }
     // init (connect etc)
     $agent->init();
     if ($once) {
         self::$agents[$name] = $agent;
     }
     return $agent;
 }