If you want to avoid this code in your class using the cache, the NullDriver and a possible answer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class myService { [...] public function myAction() { if ($this->cache && $this->cache-exists('key')) { $val = $this->cache->get('key'); } else { $val = $otherService->getFromWebservice('key'); } if ($this->cache) { $this->cache->set('key','value'); } [...] } } |
Step 1 : In constructor, check if you have a real cache système
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
use Mactronique\PhpCache\Service\PhpCache; use Mactronique\PhpCache\Driver\NullDriver; class myService { private $cache; public function __construct(PhpCache $cache = null) { if (null === $cache) { $cache = new PhpCache(); $cache->registerDriver(new NullDriver()); } $this->cache = $cache; } [...] } |
If cache objet is null
, instantiate the null driver in a new PhpCache.
Step 2 : remove all if ($this->cache)
in your class method and use cache normally.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
use Mactronique\PhpCache\Service\PhpCache; use Mactronique\PhpCache\Driver\NullDriver; class myService { private $cache; public function __construct(PhpCache $cache = null) { if (null === $cache) { $cache = new PhpCache(); $cache->registerDriver(new NullDriver()); } $this->cache = $cache; } public function myAction() { if ($this->cache-exists('key')) { $val = $this->cache->get('key'); } else { $val = $otherService->getFromWebservice('key'); } $this->cache->set('key','value'); [...] } } |