cachingyii2

Yii2 - How does database query caching work?


Given

    public function getScheduleSelect() {
        $duration = 86400;     // cache query results for 1 day (60*60*24 secs).
        $dependency = new DbDependency();
        $dependency->sql = 'SELECT MAX(`modifieddatetime`) FROM {{%schedule}}';

        return ArrayHelper::map(
                        $this->find()
                                ->select('schedule')
                                ->orderBy('schedule')
                                ->distinct()
                                ->asArray()
                                ->cache($duration, $dependency)
                                ->all(),
                        'schedule', 'schedule');
    }

If I were to change $duration to 0 (zero), or NULL, would the cache stay forever unless the $dependency changed? Or would never check again?

Basically, what I went is to have the query run only when the $dependency changes,


Solution

  • The documentation says 0 duration means "infinity". If you pass null as duration it will use the value set in $defaultDuration property instead.

    In fact what "infinity" means depends on what caching engine you are using.

    For example yii\caching\FileCache sets expiration to 1 year when you pass 0 as duration.

    Memcache doesn't set specific expiration but your data might be removed when cache is full and needs space for new entries.

    yii\caching\ArrayCache only keeps cached data in memory so it will be available only during current request and whole cache will be gone for next request.