【问题标题】:Working with memcache with Yii and ActiveRecords使用 Yii 和 ActiveRecords 使用 memcache
【发布时间】:2015-05-26 13:29:17
【问题描述】:

所以我一直在尝试让 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,
]

根据指南 (http://www.yiiframework.com/doc-2.0/guide-caching-data.htm),这应该足以让全局缓存正常工作。据我了解,如果设置了这些变量,那么它应该在指定的时间内缓存所有查询,还是我仍然需要专门调用 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?

谢谢

【问题讨论】:

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

标签: php yii memcached yii2


【解决方案1】:

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

$enableQueryCachedocumentation 明确说明了这一点:

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

如果你真的想这样做,有办法破解它,但 IMO 不值得:
创建您自己的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()]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2016-01-18
    相关资源
    最近更新 更多