Memcached.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /**
  3. * Pimf
  4. *
  5. * @copyright Copyright (c) Gjero Krsteski (http://krsteski.de)
  6. * @license http://krsteski.de/new-bsd-license New BSD License
  7. */
  8. namespace Pimf;
  9. /**
  10. * For use please add the following code to the end of the config.core.php file:
  11. *
  12. * <code>
  13. *
  14. * 'cache' => array(
  15. *
  16. * 'storage' => 'memcached',
  17. * 'servers' => array(
  18. * array('host' => '127.0.0.1', 'port' => 11211, 'weight' => 100),
  19. * ),
  20. * ),
  21. * ),
  22. *
  23. * </code>
  24. *
  25. * Memcached usage:
  26. *
  27. * <code>
  28. * // Get the Memcache connection and get an item from the cache
  29. * $name = Memcached::connection()->get('name');
  30. *
  31. * // Get the Memcache connection and place an item in the cache
  32. * Memcached::connection()->set('name', 'Robin');
  33. *
  34. * // Get an item from the Memcache instance
  35. * $name = Memcached::get('name');
  36. *
  37. * // Store data on the Memcache server
  38. * Memcached::set('name', 'Robin');
  39. * </code>
  40. *
  41. * @package Pimf
  42. * @author Gjero Krsteski <[email protected]>
  43. *
  44. * @method get($key)
  45. * @method put($key, $value, $expiration)
  46. * @method forget($key);
  47. */
  48. class Memcached
  49. {
  50. /**
  51. * @var \Memcached
  52. */
  53. protected static $connection;
  54. /**
  55. * @return \Memcached
  56. */
  57. public static function connection()
  58. {
  59. if (static::$connection === null) {
  60. $conf = Registry::get('conf');
  61. static::$connection = static::connect(
  62. $conf['cache']['servers']
  63. );
  64. }
  65. return static::$connection;
  66. }
  67. /**
  68. * Create a new Memcached connection instance.
  69. *
  70. * @param array $servers
  71. * @param null $memcache
  72. *
  73. * @return \Memcached|null
  74. * @throws \RuntimeException
  75. */
  76. protected static function connect(array $servers, $memcache = null)
  77. {
  78. if (!$memcache) {
  79. $memcache = new \Memcached();
  80. }
  81. foreach ($servers as $server) {
  82. $memcache->addServer($server['host'], $server['port'], $server['weight']);
  83. }
  84. if ($memcache->getVersion() === false) {
  85. throw new \RuntimeException('could not establish memcached connection!');
  86. }
  87. return $memcache;
  88. }
  89. /**
  90. * Dynamically pass all other method calls to the Memcache instance.
  91. *
  92. * @param $method
  93. * @param $parameters
  94. *
  95. * @return mixed
  96. */
  97. public static function __callStatic($method, $parameters)
  98. {
  99. return call_user_func_array(array(static::connection(), $method), $parameters);
  100. }
  101. }