You are here

public function MemcacheDriverFactory::get in Memcache API and Integration 8.2

Returns a Memcache object based on settings and the bin requested.

Parameters

string $bin: The bin which is to be used.

bool $flush: Rebuild the bin/server/cache mapping.

Return value

\Drupal\memcache\DrupalMemcacheInterface|bool A Memcache object.

File

src/Driver/MemcacheDriverFactory.php, line 94

Class

MemcacheDriverFactory
Factory class for creation of Memcache objects.

Namespace

Drupal\memcache\Driver

Code

public function get($bin = NULL, $flush = FALSE) {
  if ($flush) {
    $this
      ->flush();
  }
  if (empty($this->connections) || empty($this->connections[$bin])) {

    // If there is no cluster for this bin in $bins, cluster is
    // 'default'.
    $cluster = empty($this->bins[$bin]) ? 'default' : $this->bins[$bin];

    // If this bin isn't in our $bins configuration array, and the
    // 'default' cluster is already initialized, map the bin to 'default'
    // because we always map the 'default' bin to the 'default' cluster.
    if (empty($this->bins[$bin]) && !empty($this->connections['default'])) {
      $this->connections[$bin] =& $this->connections['default'];
    }
    else {

      // Create a new Memcache object. Each cluster gets its own Memcache
      // object.

      /** @var \Drupal\memcache\Connection\MemcacheConnectionInterface $memcache */
      $memcache = new $this->connectionClass($this->settings);

      // A variable to track whether we've connected to the first server.
      $init = FALSE;

      // Link all the servers to this cluster.
      foreach ($this->servers as $s => $c) {
        if ($c == $cluster && !isset($this->failedConnectionCache[$s])) {
          if ($memcache
            ->addServer($s, $this->persistent) && !$init) {
            $init = TRUE;
          }
          if (!$init) {
            $this->failedConnectionCache[$s] = FALSE;
          }
        }
      }
      if ($init) {

        // Map the current bin with the new Memcache object.
        $this->connections[$bin] = $memcache;

        // Now that all the servers have been mapped to this cluster, look for
        // other bins that belong to the cluster and map them too.
        foreach ($this->bins as $b => $c) {
          if ($c == $cluster && $b != $bin) {

            // Map this bin and cluster by reference.
            $this->connections[$b] =& $this->connections[$bin];
          }
        }
      }
      else {
        throw new MemcacheException('Memcache instance could not be initialized. Check memcache is running and reachable');
      }
    }
  }
  return empty($this->connections[$bin]) ? FALSE : new $this->driverClass($this->settings, $this->connections[$bin]
    ->getMemcache(), $bin);
}