We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Disable ORM cache during development and for testing

Hi,

Using phalcon 2.0.1, I have added ORM caching to my project:

$di->set('modelsCache', function () use () {
    $frontCache = new FrontData(
        array(
            "lifetime" => 172800
        )
    );
    $cache = new BackFile(
        $frontCache,
        array(
            "cacheDir" => $directory,
        )
    );
    return $cache;
}

Now I would like to disable this during development and for automated testing. I use the ORM caching in the form:

MyObject::find(array(
    'id != :id:',
    'bind' => array(
        'id' => $id,
    ),
    'cache' => array(
        'key' => 'my_cache_key',
        'lifetime' => 3600,
    ),
))

If I simply omit adding the cache component to the dependency injection container, the cache component will complain as soon as I call a find method with the cache key.

The logged error is:

Service 'modelsCache' wasn't found in the dependency injection container

So, how can I disable the Cache? Anyway of stubbing the Backend Cache? I know that I could create a dummy Backend Cache component that implements the BackendInterface, but I figured that there must be a way of disabling the cache.



85.5k

hi,

$this->di->set('modelsCache', function(){

            $frontCache = new FrontendData(
                array(
                    "lifetime" => 186400
                )
            );

            $cache = new Redis($frontCache, array(
                'host' => '127.0.0.1',
                'port' => 6379,
                "statsKey" => '_PHCM'
            ));

            if (APPLICATION_ENV === 'development'){
                $cache->flush();
            }

            return $cache;
        }, true);

Could you just set the cache lifetime to 1?



993
edited Dec '15

What about this

class NoneBackend extends \Phalcon\Cache\Backend implements \Phalcon\Cache\BackendInterface
{
    public function delete($keyName)
    {
    }

    public function exists($keyName = null, $lifetime = null)
    {
    }

    public function get($keyName, $lifetime = null)
    {
    }

    public function queryKeys($prefix = null)
    {
    }

    public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true)
    {
    }
}

For phpunit I created Mock class,

$cacheMock = $this->createMock( \Phalcon\Cache\Backend\Redis::class);

$cacheMock->expects($this->any()) ->method('save')->willReturn(true);

$cacheMock->expects($this->any()) ->method('get')->willReturn(null);

$cacheMock->expects($this->any()) ->method('delete')->willReturn(true);

$cacheMock->expects($this->any()) ->method('exists')->willReturn(true);

$this->di->getService('modelsCache') ->setSharedInstance($cacheMock);