php - PhalconMvcModels - model relationship and caching

98

There's this in Phalcon docs:

http://docs.phalconphp.com/en/latest/reference/models.html#taking-advantage-of-relationships.

Suppose I have a code like this:

public function initialize()
{
    $this->hasMany("id", "RobotsParts", "robots_id");
}

/**
 * Return the related "robots parts"
 *
 * @return \RobotsParts[]
 */
public function getRobotsParts($parameters=null)
{
    return $this->getRelated('RobotsParts', $parameters);
}

I wonder what is the best approach to cache what "->getRelated()" lookup is producing? Meaning, it should not go to database if it gets called more than once.

Thanks!

293

Answer

Solution:

Assuming that you have defined your cache mechanism in the service container, you can do this:

public function getRobotsParts($parameters=null)
{
    $di  = \Phalcon\DI::getDefault();
    $key = 'cache_robots_parts_' . $this->id;

    $cache = $di->cache->get($key);

    if (null == $cache) {
        $results = $this->getRelated('RobotsParts', $parameters);
    } else {
        $results = $cache;
    }

    return $results;
}
920

Answer

Solution:

It may be written on the short way:

public function getRobotsParts($parameters=null)
{
    $parameters['cache'] = array(
        'lifetime' => 123,
        'key'      => 'cache_robots_parts_' . $this->id,
    );

    return $this->getRelated('RobotsParts', $parameters);
}

Or more short, if$parameters['cache'] set in method, which caused this

People are also looking for solutions to the problem: php - Null string returned from function but can print/echo inside function

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.