Cache.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. /**
  3. * Kohana Cache provides a common interface to a variety of caching engines. Tags are
  4. * supported where available natively to the cache system. Kohana Cache supports multiple
  5. * instances of cache engines through a grouped singleton pattern.
  6. *
  7. * ### Supported cache engines
  8. *
  9. * * [APC](http://php.net/manual/en/book.apc.php)
  10. * * [eAccelerator](http://eaccelerator.net/)
  11. * * File
  12. * * [Memcache](http://memcached.org/)
  13. * * [Memcached-tags](http://code.google.com/p/memcached-tags/)
  14. * * [SQLite](http://www.sqlite.org/)
  15. * * [Xcache](http://xcache.lighttpd.net/)
  16. *
  17. * ### Introduction to caching
  18. *
  19. * Caching should be implemented with consideration. Generally, caching the result of resources
  20. * is faster than reprocessing them. Choosing what, how and when to cache is vital. PHP APC is
  21. * presently one of the fastest caching systems available, closely followed by Memcache. SQLite
  22. * and File caching are two of the slowest cache methods, however usually faster than reprocessing
  23. * a complex set of instructions.
  24. *
  25. * Caching engines that use memory are considerably faster than the file based alternatives. But
  26. * memory is limited whereas disk space is plentiful. If caching large datasets it is best to use
  27. * file caching.
  28. *
  29. * ### Configuration settings
  30. *
  31. * Kohana Cache uses configuration groups to create cache instances. A configuration group can
  32. * use any supported driver, with successive groups using the same driver type if required.
  33. *
  34. * #### Configuration example
  35. *
  36. * Below is an example of a _memcache_ server configuration.
  37. *
  38. * return array(
  39. * 'memcache' => array( // Name of group
  40. * 'driver' => 'memcache', // using Memcache driver
  41. * 'servers' => array( // Available server definitions
  42. * array(
  43. * 'host' => 'localhost',
  44. * 'port' => 11211,
  45. * 'persistent' => FALSE
  46. * )
  47. * ),
  48. * 'compression' => FALSE, // Use compression?
  49. * ),
  50. * )
  51. *
  52. * In cases where only one cache group is required, set `Cache::$default` (in your bootstrap,
  53. * or by extending `Kohana_Cache` class) to the name of the group, and use:
  54. *
  55. * $cache = Cache::instance(); // instead of Cache::instance('memcache')
  56. *
  57. * It will return the cache instance of the group it has been set in `Cache::$default`.
  58. *
  59. * #### General cache group configuration settings
  60. *
  61. * Below are the settings available to all types of cache driver.
  62. *
  63. * Name | Required | Description
  64. * -------------- | -------- | ---------------------------------------------------------------
  65. * driver | __YES__ | (_string_) The driver type to use
  66. *
  67. * Details of the settings specific to each driver are available within the drivers documentation.
  68. *
  69. * ### System requirements
  70. *
  71. * * Kohana 3.0.x
  72. * * PHP 5.2.4 or greater
  73. *
  74. * @package Kohana/Cache
  75. * @category Base
  76. * @version 2.0
  77. * @author Kohana Team
  78. * @copyright (c) Kohana Team
  79. * @license https://koseven.ga/LICENSE.md
  80. */
  81. abstract class Kohana_Cache {
  82. const DEFAULT_EXPIRE = 3600;
  83. /**
  84. * @var string default driver to use
  85. */
  86. public static $default = 'file';
  87. /**
  88. * @var Kohana_Cache instances
  89. */
  90. public static $instances = [];
  91. /**
  92. * Creates a singleton of a Kohana Cache group. If no group is supplied
  93. * the __default__ cache group is used.
  94. *
  95. * // Create an instance of the default group
  96. * $default_group = Cache::instance();
  97. *
  98. * // Create an instance of a group
  99. * $foo_group = Cache::instance('foo');
  100. *
  101. * // Access an instantiated group directly
  102. * $foo_group = Cache::$instances['default'];
  103. *
  104. * @param string $group the name of the cache group to use [Optional]
  105. * @return Cache
  106. * @throws Cache_Exception
  107. */
  108. public static function instance($group = NULL)
  109. {
  110. // If there is no group supplied, try to get it from the config
  111. if ($group === NULL)
  112. {
  113. $group = Kohana::$config->load('cache.default');
  114. }
  115. // If there is no group supplied
  116. if ($group === NULL)
  117. {
  118. // Use the default setting
  119. $group = Cache::$default;
  120. }
  121. if (isset(Cache::$instances[$group]))
  122. {
  123. // Return the current group if initiated already
  124. return Cache::$instances[$group];
  125. }
  126. $config = Kohana::$config->load('cache');
  127. if ( ! $config->offsetExists($group))
  128. {
  129. throw new Cache_Exception(
  130. 'Failed to load Kohana Cache group: :group',
  131. [':group' => $group]
  132. );
  133. }
  134. $config = $config->get($group);
  135. // Create a new cache type instance
  136. $cache_class = 'Cache_'.ucfirst($config['driver']);
  137. Cache::$instances[$group] = new $cache_class($config);
  138. // Return the instance
  139. return Cache::$instances[$group];
  140. }
  141. /**
  142. * @var Config
  143. */
  144. protected $_config = [];
  145. /**
  146. * Ensures singleton pattern is observed, loads the default expiry
  147. *
  148. * @param array $config configuration
  149. */
  150. protected function __construct(array $config)
  151. {
  152. $this->config($config);
  153. }
  154. /**
  155. * Getter and setter for the configuration. If no argument provided, the
  156. * current configuration is returned. Otherwise the configuration is set
  157. * to this class.
  158. *
  159. * // Overwrite all configuration
  160. * $cache->config(array('driver' => 'memcache', '...'));
  161. *
  162. * // Set a new configuration setting
  163. * $cache->config('servers', array(
  164. * 'foo' => 'bar',
  165. * '...'
  166. * ));
  167. *
  168. * // Get a configuration setting
  169. * $servers = $cache->config('servers);
  170. *
  171. * @param mixed key to set to array, either array or config path
  172. * @param mixed value to associate with key
  173. * @return mixed
  174. */
  175. public function config($key = NULL, $value = NULL)
  176. {
  177. if ($key === NULL)
  178. return $this->_config;
  179. if (is_array($key))
  180. {
  181. $this->_config = $key;
  182. }
  183. else
  184. {
  185. if ($value === NULL)
  186. return Arr::get($this->_config, $key);
  187. $this->_config[$key] = $value;
  188. }
  189. return $this;
  190. }
  191. /**
  192. * Overload the __clone() method to prevent cloning
  193. *
  194. * @return void
  195. * @throws Cache_Exception
  196. */
  197. final public function __clone()
  198. {
  199. throw new Cache_Exception('Cloning of Kohana_Cache objects is forbidden');
  200. }
  201. /**
  202. * Retrieve a cached value entry by id.
  203. *
  204. * // Retrieve cache entry from default group
  205. * $data = Cache::instance()->get('foo');
  206. *
  207. * // Retrieve cache entry from default group and return 'bar' if miss
  208. * $data = Cache::instance()->get('foo', 'bar');
  209. *
  210. * // Retrieve cache entry from memcache group
  211. * $data = Cache::instance('memcache')->get('foo');
  212. *
  213. * @param string $id id of cache to entry
  214. * @param string $default default value to return if cache miss
  215. * @return mixed
  216. * @throws Cache_Exception
  217. */
  218. abstract public function get($id, $default = NULL);
  219. /**
  220. * Set a value to cache with id and lifetime
  221. *
  222. * $data = 'bar';
  223. *
  224. * // Set 'bar' to 'foo' in default group, using default expiry
  225. * Cache::instance()->set('foo', $data);
  226. *
  227. * // Set 'bar' to 'foo' in default group for 30 seconds
  228. * Cache::instance()->set('foo', $data, 30);
  229. *
  230. * // Set 'bar' to 'foo' in memcache group for 10 minutes
  231. * if (Cache::instance('memcache')->set('foo', $data, 600))
  232. * {
  233. * // Cache was set successfully
  234. * return
  235. * }
  236. *
  237. * @param string $id id of cache entry
  238. * @param string $data data to set to cache
  239. * @param integer $lifetime lifetime in seconds
  240. * @return boolean
  241. */
  242. abstract public function set($id, $data, $lifetime = 3600);
  243. /**
  244. * Delete a cache entry based on id
  245. *
  246. * // Delete 'foo' entry from the default group
  247. * Cache::instance()->delete('foo');
  248. *
  249. * // Delete 'foo' entry from the memcache group
  250. * Cache::instance('memcache')->delete('foo')
  251. *
  252. * @param string $id id to remove from cache
  253. * @return boolean
  254. */
  255. abstract public function delete($id);
  256. /**
  257. * Delete all cache entries.
  258. *
  259. * Beware of using this method when
  260. * using shared memory cache systems, as it will wipe every
  261. * entry within the system for all clients.
  262. *
  263. * // Delete all cache entries in the default group
  264. * Cache::instance()->delete_all();
  265. *
  266. * // Delete all cache entries in the memcache group
  267. * Cache::instance('memcache')->delete_all();
  268. *
  269. * @return boolean
  270. */
  271. abstract public function delete_all();
  272. /**
  273. * Takes the sha1 of the id and adds prefix to avoid duplicates
  274. *
  275. * The id is converted to a sha1 to prevent any issues with
  276. * id length or any special character
  277. *
  278. * // Sanitize a cache id
  279. * $id = $this->_sanitize_id($id);
  280. *
  281. * @param string $id id of cache to sanitize
  282. * @return string
  283. */
  284. protected function _sanitize_id($id)
  285. {
  286. // adding cache prefix to avoid duplicates
  287. $prefix = '';
  288. // configuration for the specific cache group
  289. if (isset($this->_config['prefix']) AND $this->_config['prefix'] !== NULL)
  290. {
  291. $prefix = $this->_config['prefix'];
  292. }
  293. // prefix general configuration cache
  294. else
  295. {
  296. $prefix = Kohana::$config->load('cache.prefix');
  297. }
  298. // sha1 the id makes sure name is not too long and has not any not allowed characters
  299. return $prefix.sha1($id);
  300. }
  301. }
  302. // End Kohana_Cache