Php 使用Yii和ActiveRecords使用memcache

Php 使用Yii和ActiveRecords使用memcache,php,yii,memcached,yii2,Php,Yii,Memcached,Yii2,所以我一直在努力让memcache在我的网站上运行Yii 2。我已经让缓存为DB模式的东西工作,但它似乎不适用于ActiveRecord查询 这是我对数据库的配置: 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=db_name', 'username'

所以我一直在努力让memcache在我的网站上运行Yii 2。我已经让缓存为DB模式的东西工作,但它似乎不适用于ActiveRecord查询

这是我对数据库的配置:

'db' => [
    'class'                 => 'yii\db\Connection',
    'dsn'                   => 'mysql:host=127.0.0.1;dbname=db_name',
    'username'              => 'user_name',
    'password'              => 'password',
    'charset'               => 'utf8',
    'enableQueryCache'      => true,
    'queryCache'            => 'cache',
    'queryCacheDuration'    => 600,
    'enableSchemaCache'     => true,
    'schemaCache'           => 'cache',
    'schemaCacheDuration'   => 3600,
]
根据指南(),这应该足以让全局缓存工作。根据我的理解,如果设置了这些变量,那么它应该在指定的时间内缓存所有查询,或者我还需要使用以下命令专门调用if吗

$result = Customer::getDb()->cache(function ($db) {
    return Customer::find()->where(['id' => 1])->one();
});
我深入研究了代码库以了解发生了什么,它在
\yii\db\Connection::getQueryCacheInfo()
中的外观被更改为如下开头:它将完美地工作:

public function getQueryCacheInfo($duration, $dependency)
{

    if (!$this->enableQueryCache) {
        return null;
    }

    $duration = (isset($duration)) ? $duration : $this->queryCacheDuration;
    $dependency = (isset($dependency)) ? $dependency : $this->queryCache;
我做错什么了吗?为什么我不能让memcache默认用于所有查询


谢谢

如果您真的想缓存“所有查询”,最好启用数据库的查询缓存。这样做要好得多。除了数据库模式之外,除非您显式地启用它,否则不会进行缓存,如您的示例中所示

for
$enableQueryCache
明确指出:

是否启用查询缓存。请注意,为了启用查询缓存,必须启用由$queryCache指定的有效缓存组件,并且必须将$enableQueryCache设置为true此外,只有包含在cache()中的查询结果才会被缓存。

如果你真的想这么做,有一种方法可以破解,但我觉得不值得:
创建自己的
ActiveQuery
派生类。在其
createCommand()
方法中,已在返回命令对象之前启用缓存:

class MyActiveQuery extends ActiveQuery 
{
   public function createCommand($db = null)
   {
      $command = parent::createCommand(db);
      $command->cache();
      return $command;
   }
}
然后,您必须重写希望缓存的每个
ActiveRecord
类的
find()
-方法,以返回一个
ActiveQuery
实例

public static function find()
{
    return Yii::createObject(MyActiveQuery::className(), [get_called_class()]);
}

如果确实希望缓存“所有查询”,最好启用数据库的查询缓存。这样做要好得多。除了数据库模式之外,除非您显式地启用它,否则不会进行缓存,如您的示例中所示

for
$enableQueryCache
明确指出:

是否启用查询缓存。请注意,为了启用查询缓存,必须启用由$queryCache指定的有效缓存组件,并且必须将$enableQueryCache设置为true此外,只有包含在cache()中的查询结果才会被缓存。

如果你真的想这么做,有一种方法可以破解,但我觉得不值得:
创建自己的
ActiveQuery
派生类。在其
createCommand()
方法中,已在返回命令对象之前启用缓存:

class MyActiveQuery extends ActiveQuery 
{
   public function createCommand($db = null)
   {
      $command = parent::createCommand(db);
      $command->cache();
      return $command;
   }
}
然后,您必须重写希望缓存的每个
ActiveRecord
类的
find()
-方法,以返回一个
ActiveQuery
实例

public static function find()
{
    return Yii::createObject(MyActiveQuery::className(), [get_called_class()]);
}

仅供参考:
return Customer::findOne(1)也可以。@Blizz,是的,那只是Yii文档的复制粘贴。仅供参考:
return Customer::findOne(1)也可以。@Blizz,是的,那只是Yii文档的复制粘贴。