Skip to content

Instantly share code, notes, and snippets.

@jkovacs618
Created August 26, 2014 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkovacs618/4992eb0e82bfac08373c to your computer and use it in GitHub Desktop.
Save jkovacs618/4992eb0e82bfac08373c to your computer and use it in GitHub Desktop.
Yii2 custom AppActiveRecord class used to extend yii\db\ActiveRecord to provide a static find($config) function for backwards-compatibility with Yii 1.1 CActiveRecord->find*(array) functions.
<?php
namespace common\models\db;
class AppActiveRecord extends \yii\db\ActiveRecord
{
/**
* Override the \yii\db\ActiveRecord::find() static function to allow passing in an array of configuration properties.
* Also, return a custom AppActiveQuery object that overrides functionality of ActiveQuery and allows Caching.
*
* @param Array|null $config The array of key value pairs to set the ActiveQuery properties on construction.
* @return \common\models\db\AppActiveQuery
*/
public static function find($config = null)
{
$activeQuery = \Yii::createObject(\common\models\db\AppActiveQuery::className(), [get_called_class()]);
if(is_array($config) && sizeof($config) > 0) {
if(isset($config['select']) && is_string($config['select'])) {
$config['select'] = self::_selectStringToArray($config['select']);
}
if(isset($config['orderBy']) && is_string($config['orderBy'])) {
$config['orderBy'] = self::_orderByStringToArray($config['orderBy']);
}
if(!isset($config['from'])) {
// If the 'from' clause is not specified, create one using the called class Table Name.
// Include the default table alias of 't' for backwards compatibility. Store 'from' as an array of one string.
$className = get_called_class();
$tableName = $className::tableName();
$config['from'] = [$tableName.' t'];
}
foreach($config as $key => $value) {
$activeQuery->$key = $value;
}
}
return $activeQuery;
}
public static function _selectStringToArray($string) {
$array = explode(',',$string);
if(is_array($array) && sizeof($array) > 0) {
foreach($array as $index => $column) {
$array[$index] = trim($column);
}
}
return $array;
}
public static function _orderByStringToArray($string) {
$strings = explode(',',$string);
$orderByArray = array();
if(is_array($strings) && sizeof($strings) > 0) {
foreach($strings as $index => $orderBy) {
$orderBy = trim($orderBy);
$lastSpacePos = strrpos($orderBy,' ');
$sort = SORT_ASC;
if($lastSpacePos!==false) {
$column = substr($orderBy,0,$lastSpacePos);
$sort = strtoupper(substr($orderBy,$lastSpacePos));
if($sort === 'DESC') {
$sort = SORT_DESC;
}
}
else {
$column = $orderBy;
}
$orderByArray[$column] = $sort;
}
}
return $orderByArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment