memcached.php 1.54 KB
Newer Older
1 2 3 4 5 6 7
<?php namespace Laravel;

class Memcached {

	/**
	 * The Memcached connection instance.
	 *
8
	 * @var Memcached
9
	 */
10
	protected static $connection;
11 12 13 14

	/**
	 * Get the Memcached connection instance.
	 *
15 16 17 18 19 20 21
	 * <code>
	 *		// Get the Memcache connection and get an item from the cache
	 *		$name = Memcached::connection()->get('name');
	 *
	 *		// Get the Memcache connection and place an item in the cache
	 *		Memcached::connection()->set('name', 'Taylor');
	 * </code>
22
	 *
Phill Sparks committed
23
	 * @return Memcached
24
	 */
25
	public static function connection()
26
	{
27
		if (is_null(static::$connection))
28
		{
29
			static::$connection = static::connect(Config::get('cache.memcached'));
30 31
		}

32
		return static::$connection;
33 34 35 36 37
	}

	/**
	 * Create a new Memcached connection instance.
	 *
38
	 * @param  array      $servers
Phill Sparks committed
39
	 * @return Memcached
40
	 */
41
	protected static function connect($servers)
42
	{
43
		$memcache = new \Memcached;
44 45 46

		foreach ($servers as $server)
		{
47
			$memcache->addServer($server['host'], $server['port'], $server['weight']);
48 49 50 51
		}

		if ($memcache->getVersion() === false)
		{
52
			throw new \Exception('Could not establish memcached connection.');
53 54 55 56 57
		}

		return $memcache;
	}

58 59 60 61 62 63 64 65 66 67 68 69 70
	/**
	 * Dynamically pass all other method calls to the Memcache instance.
	 *
	 * <code>
	 *		// Get an item from the Memcache instance
	 *		$name = Memcached::get('name');
	 *
	 *		// Store data on the Memcache server
	 *		Memcached::set('name', 'Taylor');
	 * </code>
	 */
	public static function __callStatic($method, $parameters)
	{
71
		return call_user_func_array(array(static::connection(), $method), $parameters);
72 73
	}

74
}