【问题标题】:Phalcon\Mvc\Models - model relationship and cachingPhalcon\Mvc\Models - 模型关系和缓存
【发布时间】:2013-11-06 14:49:29
【问题描述】:

Phalcon 文档中有这个:

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

假设我有这样的代码:

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

我想知道缓存“->getRelated()”查找产生的内容的最佳方法是什么?意思是,如果它被多次调用,它不应该进入数据库。

谢谢!

【问题讨论】:

    标签: php phalcon


    【解决方案1】:

    假设你已经在服务容器中定义了你的缓存机制,你可以这样做:

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

    【讨论】:

    • 谢谢,这是显而易见的事情。我想知道 $obj->_modelsManager 是否具有内置缓存功能。
    • 缓存策略存在,但请求终止后释放。有关更多信息,您可以查看此docs.phalconphp.com/en/latest/reference/…
    【解决方案2】:

    可以写成短途:

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

    或者更短一点,如果在方法中设置了$parameters['cache'],就会导致这种情况

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      相关资源
      最近更新 更多