Question

Following this document, I'm trying to retrieve memcached key within find() method in a model (in order to get cache version of the model&relations).

Does somebody know how should i access the memcached object which i set at the DI?

class Tags extends Phalcon\Mvc\Model {

protected  function _getCache($key)
{
    // how do i retreive memcached object?

}

protected static function _setCache($key)
{
    // stores data in the cache
}

these are the settings as they are in DI:

$di->set('modelsCache', function()
    {
        //Cache data for one day by default
        $frontCache = new \Phalcon\Cache\Frontend\Data(array(
                "lifetime" => 86400
        ));

        //Memcached connection settings
        $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array(
                "host" => "localhost",
                "port" => "11211"
        ));
        return $cache;

    });
Was it helpful?

Solution

First, if it's a reusable "service", use getShared() / setShared() on the DI, otherwise you will end up creating a new instance every time you access it.

To actually retrieve it from anywhere in your app:

class Tags extends Phalcon\Mvc\Model {

protected  function _getCache($key)
{
    // how do i retreive memcached object?

    $modelsChache = $this->di->getShared('modelsCache');

    // Or if DI is not set on the model, though in 99.9% it will be unless you are doing something unusual.

    $modelsChache = DI::getDefault()->getShared('modelsCache');
}

protected static function _setCache($key)
{
    // stores data in the cache
    // Same as above…
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top