Skip to content
This repository was archived by the owner on Jan 8, 2024. It is now read-only.

Commit 356a064

Browse files
committed
Optimized Cache Service: Get instances on the fly if they are requested.
1 parent f428946 commit 356a064

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

Service/Cache.php

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
*/
1313
class Cache
1414
{
15+
private $drivers = [];
16+
1517
/**
1618
* Contains all cache instances
1719
*
@@ -28,25 +30,23 @@ class Cache
2830
*/
2931
public function __construct($drivers)
3032
{
31-
foreach ($drivers['drivers'] as $name => $driver) {
32-
$this->createInstance($name, CacheManager::getInstance($driver['type'], $driver['parameters']));
33-
}
33+
$this->drivers = (array) $drivers[ 'drivers' ];
3434
}
3535

3636
/**
3737
* Set a new cache instance
3838
*
39-
* @param string $name
39+
* @param string $name
4040
* @param ExtendedCacheItemPoolInterface $instance
4141
*
4242
* @throws \phpFastCache\Exceptions\phpFastCacheDriverException
4343
*/
4444
public function createInstance($name, ExtendedCacheItemPoolInterface $instance)
4545
{
46-
if (array_key_exists($name, $this->cacheInstances) && $this->cacheInstances[$name] instanceof ExtendedCacheItemPoolInterface) {
46+
if (array_key_exists($name, $this->cacheInstances) && $this->cacheInstances[ $name ] instanceof ExtendedCacheItemPoolInterface) {
4747
throw new phpFastCacheDriverException("Cache instance '{$name}' already exists");
4848
}
49-
$this->cacheInstances[$name] = $instance;
49+
$this->cacheInstances[ $name ] = $instance;
5050
}
5151

5252
/**
@@ -61,13 +61,17 @@ public function createInstance($name, ExtendedCacheItemPoolInterface $instance)
6161
public function get($name)
6262
{
6363
if (!array_key_exists($name, $this->cacheInstances)) {
64-
throw new phpFastCacheDriverException("Cache instance '{$name}' not exists");
65-
}
66-
if (!$this->cacheInstances[$name] instanceof ExtendedCacheItemPoolInterface) {
67-
throw new phpFastCacheDriverException("Cache instance '{$name}' already instanciated");
64+
if (array_key_exists($name, $this->drivers)) {
65+
$this->createInstance($name, CacheManager::getInstance($this->drivers[ $name ][ 'type' ], $this->drivers[ $name ][ 'parameters' ]));
66+
if (!$this->cacheInstances[ $name ] instanceof ExtendedCacheItemPoolInterface) {
67+
throw new phpFastCacheDriverException("Cache instance '{$name}' does not implements ExtendedCacheItemPoolInterface");
68+
}
69+
} else {
70+
throw new phpFastCacheDriverException("Cache instance '{$name}' not exists, check your config.yml");
71+
}
6872
}
6973

70-
return $this->cacheInstances[$name];
74+
return $this->cacheInstances[ $name ];
7175
}
7276

7377
/**

0 commit comments

Comments
 (0)