memcached.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php namespace Laravel;
  2. class Memcached {
  3. /**
  4. * The Memcached connection instance.
  5. *
  6. * @var Memcache
  7. */
  8. protected static $instance;
  9. /**
  10. * Get the Memcached connection instance.
  11. *
  12. * This connection will be managed as a singleton instance so that only
  13. * one connection to the Memcached severs will be established.
  14. *
  15. * @return Memcache
  16. */
  17. public static function instance()
  18. {
  19. if (is_null(static::$instance))
  20. {
  21. static::$instance = static::connect(Config::get('cache.memcached'));
  22. }
  23. return static::$instance;
  24. }
  25. /**
  26. * Create a new Memcached connection instance.
  27. *
  28. * The configuration array passed to this method should be an array of
  29. * server hosts / ports, like those defined in the cache configuration
  30. * file.
  31. *
  32. * <code>
  33. * // Create a new localhost Memcached connection instance.
  34. * $memcache = Memcached::connect(array('host' => '127.0.0.1', 'port' => 11211));
  35. * </code>
  36. *
  37. * @param array $servers
  38. * @return Memcache
  39. */
  40. public static function connect($servers)
  41. {
  42. $memcache = new \Memcache;
  43. foreach ($servers as $server)
  44. {
  45. $memcache->addServer($server['host'], $server['port'], true, $server['weight']);
  46. }
  47. if ($memcache->getVersion() === false)
  48. {
  49. throw new \RuntimeException('Could not establish memcached connection. Please verify your configuration.');
  50. }
  51. return $memcache;
  52. }
  53. }