PhpCache: NullDriver why ?

If you want to avoid this code in your class using the cache, the NullDriver and a possible answer.

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

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.

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');

        [...]
    }
}