memcached.php 1.06 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php namespace System;

class Memcached {

	/**
	 * The Memcache instance.
	 *
	 * @var Memcache
	 */
	private static $instance = null;

	/**
	 * Get the singleton Memcache instance.
	 *
	 * @return Memcache
	 */
	public static function instance()
	{
19 20 21 22 23 24
		if (is_null(static::$instance))
		{
			static::$instance = static::connect(Config::get('cache.servers'));
		}

		return static::$instance;
25
	}
26

27 28 29
	/**
	 * Connect to the configured Memcached servers.
	 *
30
	 * @param  array     $servers
31 32
	 * @return Memcache
	 */
33
	private static function connect($servers)
34 35 36 37 38
	{
		if ( ! class_exists('Memcache'))
		{
			throw new \Exception('Attempting to use Memcached, but the Memcached PHP extension is not installed on this server.');
		}
39

40
		$memcache = new \Memcache;
41

42
		foreach ($servers as $server)
43 44 45
		{
			$memcache->addServer($server['host'], $server['port'], true, $server['weight']);
		}
46

47 48 49
		if ($memcache->getVersion() === false)
		{
			throw new \Exception('Memcached is configured. However, no connections could be made. Please verify your memcached configuration.');
50 51
		}

52
		return $memcache;
53 54 55
	}

}