yii\db\Connection::cache PHP Method

cache() public method

When query caching is enabled ([[enableQueryCache]] is true and [[queryCache]] refers to a valid cache), queries performed within the callable will be cached and their results will be fetched from cache if available. For example, php The customer will be fetched from cache if available. If not, the query will be made against DB and cached for use next time. $customer = $db->cache(function (Connection $db) { return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne(); }); Note that query cache is only meaningful for queries that return results. For queries performed with [[Command::execute()]], query cache will not be used.
See also: enableQueryCache
See also: queryCache
See also: noCache()
public cache ( callable $callable, integer $duration = null, yii\caching\Dependency $dependency = null ) : mixed
$callable callable a PHP callable that contains DB queries which will make use of query cache. The signature of the callable is `function (Connection $db)`.
$duration integer the number of seconds that query results can remain valid in the cache. If this is not set, the value of [[queryCacheDuration]] will be used instead. Use 0 to indicate that the cached data will never expire.
$dependency yii\caching\Dependency the cache dependency associated with the cached query results.
return mixed the return result of the callable
    public function cache(callable $callable, $duration = null, $dependency = null)
    {
        $this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
        try {
            $result = call_user_func($callable, $this);
            array_pop($this->_queryCacheInfo);
            return $result;
        } catch (\Exception $e) {
            array_pop($this->_queryCacheInfo);
            throw $e;
        }
    }