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!
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;
}
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