Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Yii2 custom AppActiveQuery class used to extend yii\db\ActiveQuery to provide a cache function for backwards-compatibility with Yii 1.1 CActiveRecord->cache.
<?php
namespace common\models\db;
class AppActiveQuery extends \yii\db\ActiveQuery
{
private $cacheDuration = null;
private $functionName = '';
private $q = null;
/**
* Use query caching for this ActiveQuery.
*
* @param int|null $duration Seconds to cache; Use 0 to indicate that the cached data will never expire; NULL indicates No Cache.
* @return \common\models\db\AppActiveQuery
*/
public function cache($duration = null)
{
if(!is_null($duration) && $duration >= 0) {
$this->cacheDuration = $duration;
}
return $this;
}
public function all($db = null)
{
return $this->run('all', null, $db);
}
public function one($db = null)
{
return $this->run('one', null, $db);
}
public function count($q = '*', $db = null)
{
return $this->run('count', $q, $db);
}
public function sum($q, $db = null)
{
return $this->run('sum', $q, $db);
}
public function max($q, $db = null)
{
return $this->run('max', $q, $db);
}
public function min($q, $db = null)
{
return $this->run('min', $q, $db);
}
public function average($q, $db = null)
{
return $this->run('average', $q, $db);
}
public function scalar($db = null)
{
return $this->run('scalar', null, $db);
}
public function column($db = null)
{
return $this->run('column', null, $db);
}
public function exists($db = null)
{
return $this->run('exists', null, $db);
}
protected function run($functionName, $q, $db = null)
{
$this->functionName = $functionName;
$this->q = $q;
if(is_null($db)) {
$modelClassName = $this->modelClass;
$db = $modelClassName::getDb();
}
if(!is_null($this->cacheDuration)) {
return $db->cache(function(\yii\db\Connection $db) {
$functionName = $this->functionName;
if(!is_null($this->q)) {
return parent::$functionName($this->q, $db);
}
else {
return parent::$functionName($db);
}
}, $this->cacheDuration);
}
else {
if(!is_null($this->q)) {
return parent::$functionName($this->q, $db);
}
else {
return parent::$functionName($db);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.