Пример #1
0
 /**
  * Constructor
  *
  * @param string $uniqId to be used to separate objects in addition to their key identifiers, for instance in a
  * multi-user scenario.
  *
  * @return \iveeCrest\MemcachedWrapper
  */
 public function __construct($uniqId)
 {
     $this->memcached = new \Memcached();
     $this->memcached->addServer(Config::getCacheHost(), Config::getCachePort());
     $this->memcached->setOption(\Memcached::OPT_PREFIX_KEY, Config::getCachePrefix());
     $this->uniqId = $uniqId;
 }
Пример #2
0
 /**
  * Construct the adapter, giving an array of servers.
  * @example
  *     array(
  *         'prefix' => '',
  *         'persistent_id' => '',
  *         'servers' => array(
  *             array (
  *                 'host' => 'cache1.example.com',
  *                 'port' => 11211,
  *                 'weight' => 1
  *             ),
  *             array(
  *                 'host' => 'cache2.example.com',
  *                 'port' => 11211,
  *                 'weight' => 2
  *             )
  *         )
  *     )
  * @param array $config
  */
 public function __construct(array $config = array())
 {
     try {
         if (array_key_exists('prefix', $config)) {
             $this->prefix = $config['prefix'];
         }
         if (array_key_exists('persistent_id', $config) && !empty($config['persistent_id'])) {
             // @codeCoverageIgnoreStart
             $this->memcached = new \Memcached($config['persistent_id']);
         } else {
             // @codeCoverageIgnoreEnd
             $this->memcached = new \Memcached();
         }
         foreach ($config['servers'] as $server) {
             $this->memcached->addserver($server['host'], $server['port'], $server['weight']);
         }
         if (array_key_exists('options', $config)) {
             foreach ($config['options'] as $optionKey => $optionValue) {
                 $this->memcached->setOption($optionKey, $optionValue);
             }
         }
     } catch (\Exception $e) {
         // @codeCoverageIgnoreStart
         $this->memcached = null;
         // @codeCoverageIgnoreEnd
     }
 }
Пример #3
0
 private function __construct()
 {
     $fristclassname = 'Memcached';
     $secondclassname = 'Memcache';
     $this->client_type = class_exists($fristclassname) ? $fristclassname : (class_exists($secondclassname) ? $secondclassname : FALSE);
     if ($this->client_type) {
         // 判断引入类型
         switch ($this->client_type) {
             case 'Memcached':
                 $this->m = new \Memcached('hella_connect');
                 if (count($this->m->getServerList()) == 0) {
                     $this->m->setOption(\Memcached::OPT_COMPRESSION, false);
                     // 关闭压缩功能
                     $this->m->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
                     // 使用binary二进制协议
                 } else {
                     // functionsDump ( $this->m->getServerList () );
                 }
                 break;
             case 'Memcache':
                 $this->m = new \Memcache();
                 // if (auto_compress_tresh){
                 // $this->setcompressthreshold(auto_compress_tresh, auto_compress_savings);
                 // }
                 break;
         }
         $this->auto_connect();
     } else {
         echo 'ERROR: Failed to load Memcached or Memcache Class (∩_∩)';
         exit;
     }
 }
Пример #4
0
 protected function __construct()
 {
     if (class_exists('\\Memcached')) {
         $m = new \Memcached("memcached_pool");
         $m->setOption(\Memcached::OPT_BINARY_PROTOCOL, TRUE);
         // some nicer default options
         $m->setOption(\Memcached::OPT_NO_BLOCK, TRUE);
         $m->setOption(\Memcached::OPT_AUTO_EJECT_HOSTS, TRUE);
         // We use a consistent connection to memcached, so only add in the
         // servers first time through otherwise we end up duplicating our
         // connections to the server.
         if (!$m->getServerList()) {
             // parse server config
             $servers = explode(",", MEMCACHE_SERVERS);
             foreach ($servers as $s) {
                 $parts = explode(":", $s);
                 $m->addServer($parts[0], $parts[1]);
             }
         }
         // setup authentication
         if (defined('MEMCACHE_USERNAME') && defined('MEMCACHE_PASSWORD')) {
             $m->setSaslAuthData(MEMCACHE_USERNAME, MEMCACHE_PASSWORD);
         }
         $this->memcache = $m;
     }
 }
Пример #5
0
 /**
  * Create the Memcached connection
  *
  * @return  void
  *
  * @since   12.1
  * @throws  RuntimeException
  */
 protected function getConnection()
 {
     if (!static::isSupported()) {
         throw new RuntimeException('Memcached Extension is not available');
     }
     $config = JFactory::getConfig();
     $host = $config->get('memcached_server_host', 'localhost');
     $port = $config->get('memcached_server_port', 11211);
     // Create the memcached connection
     if ($config->get('memcached_persist', true)) {
         static::$_db = new Memcached($this->_hash);
         $servers = static::$_db->getServerList();
         if ($servers && ($servers[0]['host'] != $host || $servers[0]['port'] != $port)) {
             static::$_db->resetServerList();
             $servers = array();
         }
         if (!$servers) {
             static::$_db->addServer($host, $port);
         }
     } else {
         static::$_db = new Memcached();
         static::$_db->addServer($host, $port);
     }
     static::$_db->setOption(Memcached::OPT_COMPRESSION, $this->_compress);
     $stats = static::$_db->getStats();
     $result = !empty($stats["{$host}:{$port}"]) && $stats["{$host}:{$port}"]['pid'] > 0;
     if (!$result) {
         // Null out the connection to inform the constructor it will need to attempt to connect if this class is instantiated again
         static::$_db = null;
         throw new JCacheExceptionConnecting('Could not connect to memcached server');
     }
 }
Пример #6
0
 public function init($config)
 {
     global $_G;
     if (!$config) {
         if (TAE) {
             $config["host"] = "127.0.0.1";
             $config["port"] = 11211;
         } else {
             $config = $_G['_config']['cache_config'];
         }
     }
     $this->config = $config;
     $connect = new Memcached();
     //声明一个新的memcached链接
     $connect->setOption(Memcached::OPT_COMPRESSION, false);
     //关闭压缩功能
     $connect->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
     //使用binary二进制协议
     $connect->addServer($config['host'], $config['port']);
     //添加OCS实例地址及端口号
     if ($config['username'] && $config['password']) {
         //设置OCS帐号密码进行鉴权,如已开启免密码功能,则无需此步骤
         $connect->setSaslAuthData($config['username'], $config['password']);
     }
     $this->enable = true;
     $this->obj = $connect;
     return $this->enable;
 }
Пример #7
0
 /**
  * Return memcached connection object
  *
  * @return  object   memcached connection object
  *
  * @since   12.1
  */
 protected function getConnection()
 {
     if ((extension_loaded('memcached') && class_exists('Memcached')) != true) {
         return false;
     }
     $config = JFactory::getConfig();
     $this->_persistent = $config->get('memcache_persist', true);
     $this->_compress = $config->get('memcache_compress', false) == false ? 0 : Memcached::OPT_COMPRESSION;
     /*
      * This will be an array of loveliness
      * @todo: multiple servers
      * $servers	= (isset($params['servers'])) ? $params['servers'] : array();
      */
     $server = array();
     $server['host'] = $config->get('memcache_server_host', 'localhost');
     $server['port'] = $config->get('memcache_server_port', 11211);
     // Create the memcache connection
     if ($this->_persistent) {
         $session = JFactory::getSession();
         self::$_db = new Memcached($session->getId());
     } else {
         self::$_db = new Memcached();
     }
     $memcachedtest = self::$_db->addServer($server['host'], $server['port']);
     if ($memcachedtest == false) {
         return JError::raiseError(404, "Could not connect to memcached server");
     }
     self::$_db->setOption(Memcached::OPT_COMPRESSION, $this->_compress);
     // Memcached has no list keys, we do our own accounting, initialise key index
     if (self::$_db->get($this->_hash . '-index') === false) {
         $empty = array();
         self::$_db->set($this->_hash . '-index', $empty, 0);
     }
     return;
 }
Пример #8
0
 /**
  * {@inheritdoc}
  */
 public function write($key, $data, $expires = 60, $compressed = false)
 {
     $cmp = $this->driver->getOption(Memcached::OPT_COMPRESSION);
     $this->driver->setOption(Memcached::OPT_COMPRESSION, $compressed);
     $cached = $this->driver->set($key, $data, $expires);
     $this->driver->setOption(Memcached::OPT_COMPRESSION, $cmp);
     return $cached;
 }
Пример #9
0
 protected function getBackend()
 {
     $memcached = new Memcached();
     $memcached->addServer('localhost', 11211);
     $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
     $memcached->setOption(Memcached::OPT_TCP_NODELAY, true);
     return Matryoshka\Memcached::create($memcached);
 }
Пример #10
0
 /**
  * Constructor
  * @param array $options cache store storage option
  */
 public function __construct($options = array())
 {
     $this->connect = new \Memcached();
     $this->prefix = $options['prefix'];
     $this->default_ttl = $options['default_ttl'];
     $this->connect->setOption(\Memcached::OPT_PREFIX_KEY, $this->prefix);
     $this->connect->addServers($options['servers']);
 }
Пример #11
0
 /**
  * {@inheritdoc}
  */
 public function connect()
 {
     foreach ($this->options['options'] as $option => $value) {
         $this->service->setOption($option, $value);
     }
     foreach ($this->options['servers'] as $server) {
         $server = $server + $this->options['defaultServer'];
         $this->service->addServer($server['host'], $server['port'], $server['weight']);
     }
 }
Пример #12
0
 /**
  * @param       $persistentId
  * @param array $connections
  */
 public function __construct($persistentId, array $connections)
 {
     $this->isMemcachedExtensionAvailable();
     $this->memcached = new MemcachedDriver($persistentId);
     $this->memcached->addServers($connections);
     $this->memcached->setOption(MemcachedDriver::OPT_SERIALIZER, \defined(MemcachedDriver::HAVE_IGBINARY) && MemcachedDriver::HAVE_IGBINARY ? MemcachedDriver::SERIALIZER_IGBINARY : MemcachedDriver::SERIALIZER_PHP);
     $this->memcached->setOption(MemcachedDriver::OPT_DISTRIBUTION, MemcachedDriver::DISTRIBUTION_CONSISTENT);
     $this->memcached->setOption(MemcachedDriver::OPT_LIBKETAMA_COMPATIBLE, true);
     $this->memcached->setOption(MemcachedDriver::OPT_BINARY_PROTOCOL, true);
 }
Пример #13
0
 public function __construct()
 {
     $this->connect();
     if ($this->is_connected) {
         $this->memcached->setOption(Memcached::OPT_PREFIX_KEY, _DB_PREFIX_);
         if ($this->memcached->getOption(Memcached::HAVE_IGBINARY)) {
             $this->memcached->setOption(Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY);
         }
     }
 }
 /**
  * Constructor.
  *
  * @param \Memcached $memcached        A \Memcached instance
  * @param array      $memcachedOptions An associative array of Memcached options
  * @param array      $options          Session configuration options.
  */
 public function __construct(\Memcached $memcached, array $memcachedOptions = array(), array $options = array())
 {
     $this->memcached = $memcached;
     // defaults
     if (!isset($memcachedOptions['serverpool'])) {
         $memcachedOptions['serverpool'][] = array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 1);
     }
     $memcachedOptions['expiretime'] = isset($memcachedOptions['expiretime']) ? (int) $memcachedOptions['expiretime'] : 86400;
     $this->memcached->setOption(\Memcached::OPT_PREFIX_KEY, isset($memcachedOptions['prefix']) ? $memcachedOptions['prefix'] : 'sf2s');
     $this->memcachedOptions = $memcachedOptions;
 }
Пример #15
0
 public function init()
 {
     $this->parentInit();
     if (!$this->storage instanceof \Memcached) {
         $this->storage = new \Memcached();
         $this->normalizeServers($this->servers, $this->storage);
         $this->storage->setOption(\Memcached::OPT_COMPRESSION, true);
     }
     if ($this->serializer !== self::SERIALIZE_JSON) {
         $this->storage->setOption(\Memcached::OPT_SERIALIZER, \Memcached::SERIALIZER_PHP);
     }
 }
Пример #16
0
 /**
  * Constructor.
  */
 protected function __construct()
 {
     $this->memcached = new \Memcached();
     $this->memcached->addServer(Config::getCacheHost(), Config::getCachePort());
     $this->memcached->setOption(\Memcached::OPT_PREFIX_KEY, Config::getCachePrefix());
     //determine if deleteMulti() is supported
     if (defined('HHVM_VERSION')) {
         $this->hasMultiDelete = false;
     } else {
         $ext = new \ReflectionExtension('memcached');
         $this->hasMultiDelete = version_compare($ext->getVersion(), '2.0.0', '>=');
     }
 }
Пример #17
0
 /**
  * @param ConfigurationInterface $configuration
  */
 protected function __construct(ConfigurationInterface $configuration)
 {
     $this->configuration = $configuration;
     $this->cache = new \Memcached();
     $serverList = $this->cache->getServerList();
     if (empty($serverList)) {
         $this->cache->addServer($this->configuration->getHost(), $this->configuration->getPort());
     }
     $this->cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
     if ($this->configuration->shouldCheckConnection()) {
         $this->checkConnection();
     }
 }
Пример #18
0
 /**
  * return memcached instance
  */
 protected function memcached()
 {
     $arrConfig = $this->_arrConfig;
     if (!extension_loaded('memcached')) {
         throw_exception(__CLASS__ . '/' . __FUNCTION__ . "Memcached EXTENSION NOT INSTALLED!");
         return false;
     }
     $m = new Memcached();
     $m->setOption(Memcached::OPT_HASH, Memcached::HASH_MD5);
     $m->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
     $m->addServers($arrConfig['machines']);
     return $m;
 }
Пример #19
0
function GetMemCachedObj()
{
    static $MemCachedObj;
    if (!$MemCachedObj) {
        $MemCachedObj = new Memcached();
        if (!$MemCachedObj->addServer(MEMCACHED_HOST, MEMCACHED_PORT)) {
            throw new Exception('No se pudo conectar al Memcached: ' . $MemCachedObj->getResultMessage() . '.');
        }
        $MemCachedObj->setOption(Memcached::OPT_COMPRESSION, false);
        $MemCachedObj->setOption(Memcached::OPT_BINARY_PROTOCOL, false);
        $MemCachedObj->setOption(Memcached::OPT_CONNECT_TIMEOUT, 10000);
    }
    return $MemCachedObj;
}
Пример #20
0
 /**
  * Constructor
  *
  * @param  null|array|Traversable|MemcachedOptions $options
  * @throws Exception\ExceptionInterface
  */
 public function __construct($options = null)
 {
     if (static::$extMemcachedMajorVersion === null) {
         $v = (string) phpversion('memcached');
         static::$extMemcachedMajorVersion = $v !== '' ? (int) $v[0] : 0;
     }
     if (static::$extMemcachedMajorVersion < 1) {
         throw new Exception\ExtensionNotLoadedException('Need ext/memcached version >= 1.0.0');
     }
     parent::__construct($options);
     // It's ok to init the memcached instance as soon as possible because
     // ext/memcached auto-connects to the server on first use
     $this->memcached = new MemcachedResource();
     $options = $this->getOptions();
     // set lib options
     if (static::$extMemcachedMajorVersion > 1) {
         $this->memcached->setOptions($options->getLibOptions());
     } else {
         foreach ($options->getLibOptions() as $k => $v) {
             $this->memcached->setOption($k, $v);
         }
     }
     $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options->getNamespace());
     $servers = $options->getServers();
     if (!$servers) {
         $options->addServer('127.0.0.1', 11211);
         $servers = $options->getServers();
     }
     $this->memcached->addServers($servers);
     // get notified on change options
     $memc = $this->memcached;
     $memcMV = static::$extMemcachedMajorVersion;
     $this->getEventManager()->attach('option', function ($event) use($memc, $memcMV) {
         $params = $event->getParams();
         if (isset($params['lib_options'])) {
             if ($memcMV > 1) {
                 $memc->setOptions($params['lib_options']);
             } else {
                 foreach ($params['lib_options'] as $k => $v) {
                     $memc->setOption($k, $v);
                 }
             }
         }
         if (isset($params['namespace'])) {
             $memc->setOption(MemcachedResource::OPT_PREFIX_KEY, $params['namespace']);
         }
         // TODO: update on change/add server(s)
     });
 }
Пример #21
0
 private function connect($configServerArray)
 {
     $obj = new Memcached();
     $obj->addServer($configServerArray['host'], $configServerArray['port'], $configServerArray['height']);
     if (!empty($configServerArray['auth'])) {
         $obj->setOption(Memcached::OPT_COMPRESSION, false);
         //关闭压缩功能
         $obj->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
         //使用binary二进制协议
         $auth = $configServerArray['auth'];
         $obj->setSaslAuthData($auth['user'], $auth['password']);
         //设置OCS帐号密码进行鉴权,如已开启免密码功能,则无需此步骤
     }
     return $obj;
 }
Пример #22
0
 /**
  * Constructor.
  *
  * @access  public
  * @param   array    $servers       Memcache servers
  * @param   int      $timeout       Timeout in seconds
  * @param   boolean  $compressData  Compress data?
  */
 public function __construct(array $servers, $timeout = 1, $compressData = false)
 {
     $this->memcached = new PHPMemcached();
     if ($timtout !== 1) {
         $this->memcached->setOption(PHPMemcached::OPT_CONNECT_TIMEOUT, $timeout * 1000);
         // Multiply by 1000 to convert to ms
     }
     if ($compressData === false) {
         $this->memcached->setOption(PHPMemcached::OPT_COMPRESSION, false);
     }
     // Add servers to the connection pool
     foreach ($servers as $server) {
         $this->memcached->addServer($server['server'], $server['port'], $server['weight']);
     }
 }
Пример #23
0
 /**
  * MemcachedProvider constructor
  * @param string $cache_id
  * @param string $options
  * @throws \RuntimeException
  */
 public function __construct($cache_id = null, $options = null)
 {
     //check installed library
     if (!class_exists('\\Memcached')) {
         throw new \RuntimeException("Memcached extension was not found on this server");
     }
     //create a new memcached instance with the given id
     $this->memcached = is_null($cache_id) ? new \Memcached() : new \Memcached($cache_id);
     if (is_array($options) && !empty($options)) {
         // set instance options
         foreach ($options as $option => $value) {
             $this->memcached->setOption($option, $value);
         }
     }
 }
 public function register(Application $app)
 {
     $app['memcached'] = $app->share(function () use($app) {
         $memcached = new \Memcached($app['memcached.identifier']);
         $memcached->setOption(\Memcached::OPT_COMPRESSION, false);
         $memcached->setOption(\Memcached::OPT_PREFIX_KEY, $app['memcached.prefix']);
         $serversToAdd = array_udiff($app['memcached.servers'], $memcached->getServerList(), function ($a, $b) {
             return $a['host'] == $b['host'] && $a['port'] == $b['port'] ? 0 : 1;
         });
         if (count($serversToAdd)) {
             $memcached->addServers($serversToAdd);
         }
         return $memcached;
     });
 }
Пример #25
0
function cdash_memcache_connect($server, $port)
{
    if (class_exists('Memcached')) {
        $memcached = new Memcached();
        $memcached->setOption(Memcached::OPT_COMPRESSION, true);
        global $CDASH_USE_ELASTICACHE_AUTO_DISCOVERY;
        if ($CDASH_USE_ELASTICACHE_AUTO_DISCOVERY) {
            $memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
        }
        if ($memcached->addServer($server, $port) !== false) {
            return $memcached;
        }
    }
    return false;
}
Пример #26
0
 /**
  * @param string $namespace
  * @param string $identifier
  * @param array $options
  * @throws \InvalidArgumentException
  * @throws \Leapt\CacheBundle\Exception\CacheException
  */
 public function __construct($namespace, $identifier, array $options)
 {
     parent::__construct($namespace, $identifier, $options);
     $this->driver = new \Memcached();
     $this->driver->setOption(\Memcached::OPT_PREFIX_KEY, $namespace . '.' . $identifier . '.');
     if (!isset($options['server']) || !isset($options['port'])) {
         throw new \InvalidArgumentException(sprintf('Memcached is expecting a "server" and "port" options'));
     }
     if (!$this->driver->addServer($options['server'], $options['port'])) {
         throw new CacheException('The memcached server could not be added');
     }
     if (isset($options['ttl'])) {
         $this->ttl = $options['ttl'];
     }
 }
Пример #27
0
 /**
  * Open
  *
  * Sanitizes save_path and initializes connections.
  *
  * @param    string $save_path Server path(s)
  * @param    string $name Session cookie name, unused
  * @return    bool
  */
 public function open($save_path, $name)
 {
     $this->_memcached = new Memcached();
     $this->_memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, TRUE);
     // required for touch() usage
     $server_list = array();
     foreach ($this->_memcached->getServerList() as $server) {
         $server_list[] = $server['host'] . ':' . $server['port'];
     }
     if (!preg_match_all('#,?([^,:]+)\\:(\\d{1,5})(?:\\:(\\d+))?#', $this->_config['save_path'], $matches, PREG_SET_ORDER)) {
         $this->_memcached = NULL;
         log_message('error', 'Session: Invalid Memcached save path format: ' . $this->_config['save_path']);
         return FALSE;
     }
     foreach ($matches as $match) {
         // If Memcached already has this server (or if the port is invalid), skip it
         if (in_array($match[1] . ':' . $match[2], $server_list, TRUE)) {
             log_message('debug', 'Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]);
             continue;
         }
         if (!$this->_memcached->addServer($match[1], $match[2], isset($match[3]) ? $match[3] : 0)) {
             log_message('error', 'Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.');
         } else {
             $server_list[] = $match[1] . ':' . $match[2];
         }
     }
     if (empty($server_list)) {
         log_message('error', 'Session: Memcached server pool is empty.');
         return FALSE;
     }
     return TRUE;
 }
Пример #28
0
 /**
  * Class constructor.
  *
  * @since 151216 Memcached utilities.
  *
  * @param Classes\App $App Instance of App.
  */
 public function __construct(Classes\App $App)
 {
     parent::__construct($App);
     $this->enabled = $this->App->Config->©memcache['©enabled'];
     $this->namespace = $this->App->Config->©memcache['©namespace'];
     $this->servers = $active_servers = [];
     // Initialize.
     foreach ($this->App->Config->©memcache['©servers'] as $_server) {
         $_host = $_server['©host'];
         $_port = $_server['©port'] ?? 11211;
         $_weight = $_server['©weight'] ?? 0;
         $this->servers[$_host . ':' . $_port] = [$_host, $_port, $_weight];
     }
     // unset($_server, $_host, $_port, $_weight);
     if (!class_exists('Memcached')) {
         return;
         // Not possible.
     } elseif (!$this->enabled || !$this->namespace || !$this->servers) {
         return;
         // Disabled or lacking config values.
     }
     $this->Pool = new \Memcached($this->App->namespace_sha1);
     $this->Pool->setOption(\Memcached::OPT_NO_BLOCK, true);
     $this->Pool->setOption(\Memcached::OPT_SEND_TIMEOUT, 5);
     $this->Pool->setOption(\Memcached::OPT_RECV_TIMEOUT, 5);
     $this->Pool->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
     if (\Memcached::HAVE_IGBINARY) {
         // Size and speed gains.
         $this->Pool->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
         $this->Pool->setOption(\Memcached::OPT_SERIALIZER, \Memcached::SERIALIZER_IGBINARY);
     }
     $this->maybeAddServerConnections();
 }
Пример #29
0
 public function getTestLink()
 {
     $cache = new \Memcached();
     $cache->addServer(MEMCACHE_HOST, MEMCACHE_PORT);
     $cache->setOption(Memcached::OPT_COMPRESSION, FALSE);
     return new \r8\Cache\Memcached($cache);
 }
Пример #30
0
 /**
  * Open
  *
  * Sanitizes save_path and initializes connections.
  *
  * @param    string $save_path Server path(s)
  * @param    string $name      Session cookie name, unused
  *
  * @return    bool
  */
 public function open($save_path, $name)
 {
     $this->memcached = new \Memcached();
     $this->memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
     // required for touch() usage
     $server_list = [];
     foreach ($this->memcached->getServerList() as $server) {
         $server_list[] = $server['host'] . ':' . $server['port'];
     }
     if (!preg_match_all('#,?([^,:]+)\\:(\\d{1,5})(?:\\:(\\d+))?#', $this->savePath, $matches, PREG_SET_ORDER)) {
         $this->memcached = null;
         $this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath);
         return false;
     }
     foreach ($matches as $match) {
         // If Memcached already has this server (or if the port is invalid), skip it
         if (in_array($match[1] . ':' . $match[2], $server_list, true)) {
             $this->logger->debug('Session: Memcached server pool already has ' . $match[1] . ':' . $match[2]);
             continue;
         }
         if (!$this->memcached->addServer($match[1], $match[2], isset($match[3]) ? $match[3] : 0)) {
             $this->logger->error('Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.');
         } else {
             $server_list[] = $match[1] . ':' . $match[2];
         }
     }
     if (empty($server_list)) {
         $this->logger->error('Session: Memcached server pool is empty.');
         return false;
     }
     return true;
 }