Created
August 26, 2014 16:17
-
-
Save jkovacs618/ab225ecadf55cb1feca9 to your computer and use it in GitHub Desktop.
Yii2 custom AppActiveQuery class used to extend yii\db\ActiveQuery to provide a cache function for backwards-compatibility with Yii 1.1 CActiveRecord->cache.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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