memcached.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php namespace Laravel;
  2. class Memcached {
  3. /**
  4. * The Memcached connection instance.
  5. *
  6. * @var Memcached
  7. */
  8. protected static $connection;
  9. /**
  10. * Get the Memcached connection instance.
  11. *
  12. * <code>
  13. * // Get the Memcache connection and get an item from the cache
  14. * $name = Memcached::connection()->get('name');
  15. *
  16. * // Get the Memcache connection and place an item in the cache
  17. * Memcached::connection()->set('name', 'Taylor');
  18. * </code>
  19. *
  20. * @return Memcached
  21. */
  22. public static function connection()
  23. {
  24. if (is_null(static::$connection))
  25. {
  26. static::$connection = static::connect(Config::get('cache.memcached'));
  27. }
  28. return static::$connection;
  29. }
  30. /**
  31. * Create a new Memcached connection instance.
  32. *
  33. * @param array $servers
  34. * @return Memcached
  35. */
  36. protected static function connect($servers)
  37. {
  38. $memcache = new \Memcached;
  39. foreach ($servers as $server)
  40. {
  41. $memcache->addServer($server['host'], $server['port'], $server['weight']);
  42. }
  43. if ($memcache->getVersion() === false)
  44. {
  45. throw new \Exception('Could not establish memcached connection.');
  46. }
  47. return $memcache;
  48. }
  49. /**
  50. * Dynamically pass all other method calls to the Memcache instance.
  51. *
  52. * <code>
  53. * // Get an item from the Memcache instance
  54. * $name = Memcached::get('name');
  55. *
  56. * // Store data on the Memcache server
  57. * Memcached::set('name', 'Taylor');
  58. * </code>
  59. */
  60. public static function __callStatic($method, $parameters)
  61. {
  62. return call_user_func_array(array(static::instance(), $method), $parameters);
  63. }
  64. }