5 * @link http://php-di.org/
6 * @copyright Matthieu Napoli (http://mnapoli.fr/)
7 * @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
10 namespace DI\Definition\Source;
12 use DI\Definition\CacheableDefinition;
13 use DI\Definition\Definition;
14 use Doctrine\Common\Cache\Cache;
17 * Caches another definition source.
19 * @author Matthieu Napoli <matthieu@mnapoli.fr>
21 class CachedDefinitionSource implements DefinitionSource
24 * Prefix for cache key, to avoid conflicts with other systems using the same cache
27 const CACHE_PREFIX = 'DI\\Definition\\';
30 * @var DefinitionSource
39 public function __construct(DefinitionSource $source, Cache $cache)
41 $this->source = $source;
42 $this->cache = $cache;
48 public function getDefinition($name)
51 $definition = $this->fetchFromCache($name);
53 if ($definition === false) {
54 $definition = $this->source->getDefinition($name);
57 if ($definition === null || ($definition instanceof CacheableDefinition)) {
58 $this->saveToCache($name, $definition);
68 public function getCache()
74 * Fetches a definition from the cache
76 * @param string $name Entry name
77 * @return Definition|null|boolean The cached definition, null or false if the value is not already cached
79 private function fetchFromCache($name)
81 $cacheKey = self::CACHE_PREFIX . $name;
83 $data = $this->cache->fetch($cacheKey);
85 if ($data !== false) {
93 * Saves a definition to the cache
95 * @param string $name Entry name
96 * @param Definition|null $definition
98 private function saveToCache($name, Definition $definition = null)
100 $cacheKey = self::CACHE_PREFIX . $name;
102 $this->cache->save($cacheKey, $definition);