Namespaces

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Diagnostics
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
      • Diagnostics
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • PhpGenerator
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
  • NetteModule
  • none

Classes

  • Cache
  • OutputHelper

Interfaces

  • IStorage
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  • Other releases
  • Nette homepage
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\Caching;
  9: 
 10: use Nette;
 11: use Nette\Utils\Callback;
 12: 
 13: 
 14: /**
 15:  * Implements the cache for a application.
 16:  *
 17:  * @author     David Grudl
 18:  *
 19:  * @property-read IStorage $storage
 20:  * @property-read string $namespace
 21:  */
 22: class Cache extends Nette\Object implements \ArrayAccess
 23: {
 24:     /** dependency */
 25:     const PRIORITY = 'priority',
 26:         EXPIRATION = 'expire',
 27:         EXPIRE = 'expire',
 28:         SLIDING = 'sliding',
 29:         TAGS = 'tags',
 30:         FILES = 'files',
 31:         ITEMS = 'items',
 32:         CONSTS = 'consts',
 33:         CALLBACKS = 'callbacks',
 34:         ALL = 'all';
 35: 
 36:     /** @internal */
 37:     const NAMESPACE_SEPARATOR = "\x00";
 38: 
 39:     /** @var IStorage */
 40:     private $storage;
 41: 
 42:     /** @var string */
 43:     private $namespace;
 44: 
 45:     /** @var string  last query cache used by offsetGet() */
 46:     private $key;
 47: 
 48:     /** @var mixed  last query cache used by offsetGet()  */
 49:     private $data;
 50: 
 51: 
 52:     public function __construct(IStorage $storage, $namespace = NULL)
 53:     {
 54:         $this->storage = $storage;
 55:         $this->namespace = $namespace . self::NAMESPACE_SEPARATOR;
 56:     }
 57: 
 58: 
 59:     /**
 60:      * Returns cache storage.
 61:      * @return IStorage
 62:      */
 63:     public function getStorage()
 64:     {
 65:         return $this->storage;
 66:     }
 67: 
 68: 
 69:     /**
 70:      * Returns cache namespace.
 71:      * @return string
 72:      */
 73:     public function getNamespace()
 74:     {
 75:         return (string) substr($this->namespace, 0, -1);
 76:     }
 77: 
 78: 
 79:     /**
 80:      * Returns new nested cache object.
 81:      * @param  string
 82:      * @return Cache
 83:      */
 84:     public function derive($namespace)
 85:     {
 86:         $derived = new static($this->storage, $this->namespace . $namespace);
 87:         return $derived;
 88:     }
 89: 
 90: 
 91:     /**
 92:      * Reads the specified item from the cache or generate it.
 93:      * @param  mixed key
 94:      * @param  callable
 95:      * @return mixed|NULL
 96:      */
 97:     public function load($key, $fallback = NULL)
 98:     {
 99:         $data = $this->storage->read($this->generateKey($key));
100:         if ($data === NULL && $fallback) {
101:             return $this->save($key, function (& $dependencies) use ($fallback) {
102:                 return call_user_func_array($fallback, array(& $dependencies));
103:             });
104:         }
105:         return $data;
106:     }
107: 
108: 
109:     /**
110:      * Writes item into the cache.
111:      * Dependencies are:
112:      * - Cache::PRIORITY => (int) priority
113:      * - Cache::EXPIRATION => (timestamp) expiration
114:      * - Cache::SLIDING => (bool) use sliding expiration?
115:      * - Cache::TAGS => (array) tags
116:      * - Cache::FILES => (array|string) file names
117:      * - Cache::ITEMS => (array|string) cache items
118:      * - Cache::CONSTS => (array|string) cache items
119:      *
120:      * @param  mixed  key
121:      * @param  mixed  value
122:      * @param  array  dependencies
123:      * @return mixed  value itself
124:      * @throws Nette\InvalidArgumentException
125:      */
126:     public function save($key, $data, array $dependencies = NULL)
127:     {
128:         $this->release();
129:         $key = $this->generateKey($key);
130: 
131:         if ($data instanceof Nette\Callback || $data instanceof \Closure) {
132:             $this->storage->lock($key);
133:             try {
134:                 $data = call_user_func_array($data, array(& $dependencies));
135:             } catch (\Throwable $e) {
136:                 $this->storage->remove($key);
137:                 throw $e;
138:             } catch (\Exception $e) {
139:                 $this->storage->remove($key);
140:                 throw $e;
141:             }
142:         }
143: 
144:         if ($data === NULL) {
145:             $this->storage->remove($key);
146:         } else {
147:             $this->storage->write($key, $data, $this->completeDependencies($dependencies, $data));
148:             return $data;
149:         }
150:     }
151: 
152: 
153:     private function completeDependencies($dp, $data)
154:     {
155:         if (is_object($data)) {
156:             $dp[self::CALLBACKS][] = array(array(__CLASS__, 'checkSerializationVersion'), get_class($data),
157:                 Nette\Reflection\ClassType::from($data)->getAnnotation('serializationVersion'));
158:         }
159: 
160:         // convert expire into relative amount of seconds
161:         if (isset($dp[Cache::EXPIRATION])) {
162:             $dp[Cache::EXPIRATION] = Nette\DateTime::from($dp[Cache::EXPIRATION])->format('U') - time();
163:         }
164: 
165:         // convert FILES into CALLBACKS
166:         if (isset($dp[self::FILES])) {
167:             foreach (array_unique((array) $dp[self::FILES]) as $item) {
168:                 $dp[self::CALLBACKS][] = array(array(__CLASS__, 'checkFile'), $item, @filemtime($item)); // @ - stat may fail
169:             }
170:             unset($dp[self::FILES]);
171:         }
172: 
173:         // add namespaces to items
174:         if (isset($dp[self::ITEMS])) {
175:             $dp[self::ITEMS] = array_unique(array_map(array($this, 'generateKey'), (array) $dp[self::ITEMS]));
176:         }
177: 
178:         // convert CONSTS into CALLBACKS
179:         if (isset($dp[self::CONSTS])) {
180:             foreach (array_unique((array) $dp[self::CONSTS]) as $item) {
181:                 $dp[self::CALLBACKS][] = array(array(__CLASS__, 'checkConst'), $item, constant($item));
182:             }
183:             unset($dp[self::CONSTS]);
184:         }
185: 
186:         if (!is_array($dp)) {
187:             $dp = array();
188:         }
189:         return $dp;
190:     }
191: 
192: 
193:     /**
194:      * Removes item from the cache.
195:      * @param  mixed  key
196:      * @return void
197:      */
198:     public function remove($key)
199:     {
200:         $this->save($key, NULL);
201:     }
202: 
203: 
204:     /**
205:      * Removes items from the cache by conditions.
206:      * Conditions are:
207:      * - Cache::PRIORITY => (int) priority
208:      * - Cache::TAGS => (array) tags
209:      * - Cache::ALL => TRUE
210:      * @return void
211:      */
212:     public function clean(array $conditions = NULL)
213:     {
214:         $this->release();
215:         $this->storage->clean((array) $conditions);
216:     }
217: 
218: 
219:     /**
220:      * Caches results of function/method calls.
221:      * @param  mixed
222:      * @return mixed
223:      */
224:     public function call($function)
225:     {
226:         $key = func_get_args();
227:         $key[0] = Callback::toReflection($function);
228:         return $this->load($key, function () use ($function, $key) {
229:             return Callback::invokeArgs($function, array_slice($key, 1));
230:         });
231:     }
232: 
233: 
234:     /**
235:      * Caches results of function/method calls.
236:      * @param  mixed
237:      * @param  array  dependencies
238:      * @return Closure
239:      */
240:     public function wrap($function, array $dependencies = NULL)
241:     {
242:         $cache = $this;
243:         return function () use ($cache, $function, $dependencies) {
244:             $key = array(Callback::toReflection($function), func_get_args());
245:             $data = $cache->load($key);
246:             if ($data === NULL) {
247:                 $data = $cache->save($key, Callback::invokeArgs($function, $key[1]), $dependencies);
248:             }
249:             return $data;
250:         };
251:     }
252: 
253: 
254:     /**
255:      * Starts the output cache.
256:      * @param  mixed  key
257:      * @return OutputHelper|NULL
258:      */
259:     public function start($key)
260:     {
261:         $data = $this->load($key);
262:         if ($data === NULL) {
263:             return new OutputHelper($this, $key);
264:         }
265:         echo $data;
266:     }
267: 
268: 
269:     /**
270:      * Generates internal cache key.
271:      *
272:      * @param  string
273:      * @return string
274:      */
275:     protected function generateKey($key)
276:     {
277:         return $this->namespace . md5(is_scalar($key) ? $key : serialize($key));
278:     }
279: 
280: 
281:     /********************* interface ArrayAccess ****************d*g**/
282: 
283: 
284:     /**
285:      * Inserts (replaces) item into the cache (\ArrayAccess implementation).
286:      * @param  mixed key
287:      * @param  mixed
288:      * @return void
289:      * @throws Nette\InvalidArgumentException
290:      */
291:     public function offsetSet($key, $data)
292:     {
293:         $this->save($key, $data);
294:     }
295: 
296: 
297:     /**
298:      * Retrieves the specified item from the cache or NULL if the key is not found (\ArrayAccess implementation).
299:      * @param  mixed key
300:      * @return mixed|NULL
301:      * @throws Nette\InvalidArgumentException
302:      */
303:     public function offsetGet($key)
304:     {
305:         $key = is_scalar($key) ? (string) $key : serialize($key);
306:         if ($this->key !== $key) {
307:             $this->key = $key;
308:             $this->data = $this->load($key);
309:         }
310:         return $this->data;
311:     }
312: 
313: 
314:     /**
315:      * Exists item in cache? (\ArrayAccess implementation).
316:      * @param  mixed key
317:      * @return bool
318:      * @throws Nette\InvalidArgumentException
319:      */
320:     public function offsetExists($key)
321:     {
322:         $this->release();
323:         return $this->offsetGet($key) !== NULL;
324:     }
325: 
326: 
327:     /**
328:      * Removes the specified item from the cache.
329:      * @param  mixed key
330:      * @return void
331:      * @throws Nette\InvalidArgumentException
332:      */
333:     public function offsetUnset($key)
334:     {
335:         $this->save($key, NULL);
336:     }
337: 
338: 
339:     /**
340:      * Discards the internal cache used by ArrayAccess.
341:      * @return void
342:      */
343:     public function release()
344:     {
345:         $this->key = $this->data = NULL;
346:     }
347: 
348: 
349:     /********************* dependency checkers ****************d*g**/
350: 
351: 
352:     /**
353:      * Checks CALLBACKS dependencies.
354:      * @param  array
355:      * @return bool
356:      */
357:     public static function checkCallbacks($callbacks)
358:     {
359:         foreach ($callbacks as $callback) {
360:             if (!call_user_func_array(array_shift($callback), $callback)) {
361:                 return FALSE;
362:             }
363:         }
364:         return TRUE;
365:     }
366: 
367: 
368:     /**
369:      * Checks CONSTS dependency.
370:      * @param  string
371:      * @param  mixed
372:      * @return bool
373:      */
374:     private static function checkConst($const, $value)
375:     {
376:         return defined($const) && constant($const) === $value;
377:     }
378: 
379: 
380:     /**
381:      * Checks FILES dependency.
382:      * @param  string
383:      * @param  int
384:      * @return bool
385:      */
386:     private static function checkFile($file, $time)
387:     {
388:         return @filemtime($file) == $time; // @ - stat may fail
389:     }
390: 
391: 
392:     /**
393:      * Checks object @serializationVersion label.
394:      * @param  string
395:      * @param  mixed
396:      * @return bool
397:      */
398:     private static function checkSerializationVersion($class, $value)
399:     {
400:         return Nette\Reflection\ClassType::from($class)->getAnnotation('serializationVersion') === $value;
401:     }
402: 
403: }
404: 
Nette 2.1 API documentation generated by ApiGen 2.8.0