Initial Kohana install
[speedfreak] / Server / system / libraries / Cache.php
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3  * Provides a driver-based interface for finding, creating, and deleting cached
4  * resources. Caches are identified by a unique string. Tagging of caches is
5  * also supported, and caches can be found and deleted by id or tag.
6  *
7  * $Id: Cache.php 4321 2009-05-04 01:39:44Z kiall $
8  *
9  * @package    Cache
10  * @author     Kohana Team
11  * @copyright  (c) 2007-2008 Kohana Team
12  * @license    http://kohanaphp.com/license.html
13  */
14 class Cache_Core {
15
16         protected static $instances = array();
17
18         // For garbage collection
19         protected static $loaded;
20
21         // Configuration
22         protected $config;
23
24         // Driver object
25         protected $driver;
26
27         /**
28          * Returns a singleton instance of Cache.
29          *
30          * @param   string  configuration
31          * @return  Cache_Core
32          */
33         public static function & instance($config = FALSE)
34         {
35                 if ( ! isset(Cache::$instances[$config]))
36                 {
37                         // Create a new instance
38                         Cache::$instances[$config] = new Cache($config);
39                 }
40
41                 return Cache::$instances[$config];
42         }
43
44         /**
45          * Loads the configured driver and validates it.
46          *
47          * @param   array|string  custom configuration or config group name
48          * @return  void
49          */
50         public function __construct($config = FALSE)
51         {
52                 if (is_string($config))
53                 {
54                         $name = $config;
55
56                         // Test the config group name
57                         if (($config = Kohana::config('cache.'.$config)) === NULL)
58                                 throw new Kohana_Exception('cache.undefined_group', $name);
59                 }
60
61                 if (is_array($config))
62                 {
63                         // Append the default configuration options
64                         $config += Kohana::config('cache.default');
65                 }
66                 else
67                 {
68                         // Load the default group
69                         $config = Kohana::config('cache.default');
70                 }
71
72                 // Cache the config in the object
73                 $this->config = $config;
74
75                 // Set driver name
76                 $driver = 'Cache_'.ucfirst($this->config['driver']).'_Driver';
77
78                 // Load the driver
79                 if ( ! Kohana::auto_load($driver))
80                         throw new Kohana_Exception('core.driver_not_found', $this->config['driver'], get_class($this));
81
82                 // Initialize the driver
83                 $this->driver = new $driver($this->config['params']);
84
85                 // Validate the driver
86                 if ( ! ($this->driver instanceof Cache_Driver))
87                         throw new Kohana_Exception('core.driver_implements', $this->config['driver'], get_class($this), 'Cache_Driver');
88
89                 Kohana::log('debug', 'Cache Library initialized');
90
91                 if (Cache::$loaded !== TRUE)
92                 {
93                         $this->config['requests'] = (int) $this->config['requests'];
94
95                         if ($this->config['requests'] > 0 AND mt_rand(1, $this->config['requests']) === 1)
96                         {
97                                 // Do garbage collection
98                                 $this->driver->delete_expired();
99
100                                 Kohana::log('debug', 'Cache: Expired caches deleted.');
101                         }
102
103                         // Cache has been loaded once
104                         Cache::$loaded = TRUE;
105                 }
106         }
107
108         /**
109          * Fetches a cache by id. NULL is returned when a cache item is not found.
110          *
111          * @param   string  cache id
112          * @return  mixed   cached data or NULL
113          */
114         public function get($id)
115         {
116                 // Sanitize the ID
117                 $id = $this->sanitize_id($id);
118
119                 return $this->driver->get($id);
120         }
121
122         /**
123          * Fetches all of the caches for a given tag. An empty array will be
124          * returned when no matching caches are found.
125          *
126          * @param   string  cache tag
127          * @return  array   all cache items matching the tag
128          */
129         public function find($tag)
130         {
131                 return $this->driver->find($tag);
132         }
133
134         /**
135          * Set a cache item by id. Tags may also be added and a custom lifetime
136          * can be set. Non-string data is automatically serialized.
137          *
138          * @param   string        unique cache id
139          * @param   mixed         data to cache
140          * @param   array|string  tags for this item
141          * @param   integer       number of seconds until the cache expires
142          * @return  boolean
143          */
144         function set($id, $data, $tags = NULL, $lifetime = NULL)
145         {
146                 if (is_resource($data))
147                         throw new Kohana_Exception('cache.resources');
148
149                 // Sanitize the ID
150                 $id = $this->sanitize_id($id);
151
152                 if ($lifetime === NULL)
153                 {
154                         // Get the default lifetime
155                         $lifetime = $this->config['lifetime'];
156                 }
157
158                 return $this->driver->set($id, $data, (array) $tags, $lifetime);
159         }
160
161         /**
162          * Delete a cache item by id.
163          *
164          * @param   string   cache id
165          * @return  boolean
166          */
167         public function delete($id)
168         {
169                 // Sanitize the ID
170                 $id = $this->sanitize_id($id);
171
172                 return $this->driver->delete($id);
173         }
174
175         /**
176          * Delete all cache items with a given tag.
177          *
178          * @param   string   cache tag name
179          * @return  boolean
180          */
181         public function delete_tag($tag)
182         {
183                 return $this->driver->delete($tag, TRUE);
184         }
185
186         /**
187          * Delete ALL cache items items.
188          *
189          * @return  boolean
190          */
191         public function delete_all()
192         {
193                 return $this->driver->delete(TRUE);
194         }
195
196         /**
197          * Replaces troublesome characters with underscores.
198          *
199          * @param   string   cache id
200          * @return  string
201          */
202         protected function sanitize_id($id)
203         {
204                 // Change slashes and spaces to underscores
205                 return str_replace(array('/', '\\', ' '), '_', $id);
206         }
207
208 } // End Cache