5

以这段代码为例:

public function actionPostOneWay( $postId )
{
    $dependency = new CDbCacheDependency( 'SELECT publish_date FROM posts WHERE id = :post_id;' );
    $dependency->params = array( 'post_id'=>$postId );
    $post = Post::model()->cache( 59, $dependency )->findByPk( $postId );

    // process post one way
}

public function actionPostAnotherWay( $postId )
{
    $dependency = new CDbCacheDependency( 'SELECT publish_date FROM posts WHERE id = :post_id;' );
    $dependency->params = array( 'post_id'=>$postId );
    $post = Post::model()->cache( 59, $dependency )->findByPk( $postId );

    // process post another way
}

那么访问/postOneWay/postAnotherWay重用同一个缓存对象,还是他们会创建自己的缓存对象?

4

1 回答 1

5

我试图在两个不同的操作中缓存相同的查询,是的,将使用相同的缓存对象。CProfileLogRoute可以在应用程序的配置文件中看到启用。

查看CActiveRecord类的源代码,我声明public function findByPk($pk,$condition='',$params=array())方法(和其他查询方法)使用protected function query($criteria,$all=false). 反过来,这最终依赖于Yii 使其缓存与数据库查询一起工作private function queryInternal($method,$mode,$params=array())的类。CDbCommand

可以看到用于存储和恢复查询结果的缓存键定义如下:

$cacheKey='yii:dbquery'.$this->_connection->connectionString.':'.$this->_connection->username;
$cacheKey.=':'.$this->getText().':'.serialize(array_merge($this->_paramLog,$params));
if(($result=$cache->get($cacheKey))!==false)
{
    Yii::trace('Query result found in cache','system.db.CDbCommand');
    return $result;
}

该键不考虑缓存依赖实例。CDbCacheDependency仅用于确定数据库中是否发生了某些更改,并执行新查询以更新缓存。多说 - 如果您指定不同的 SQL 以CDbCacheDependency在两个操作中创建,则只有其中一个(首先执行)将在缓存期间有意义,因为实例CDbCacheDependency与查询的结果一起被序列化缓存:

if(isset($cache,$cacheKey))
    $cache->set($cacheKey, $result, $this->_connection->queryCachingDuration, $this->_connection->queryCachingDependency);

public function set($id,$value,$expire=0,$dependency=null)在类的方法中可以看到缓存评估依赖项的实例CCache

if ($dependency !== null && $this->serializer !== false)
    $dependency->evaluateDependency();

if ($this->serializer === null)
    $value = serialize(array($value,$dependency));
elseif ($this->serializer !== false)
    $value = call_user_func($this->serializer[0], array($value,$dependency));
于 2012-11-04T19:33:00.613 回答