Class yii\redis\ActiveRecord

Inheritanceyii\redis\ActiveRecord » yii\db\BaseActiveRecord
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-redis/blob/master/src/ActiveRecord.php

ActiveRecord is the base class for classes representing relational data in terms of objects.

This class implements the ActiveRecord pattern for the redis key-value store.

For defining a record a subclass should at least implement the attributes() method to define attributes. A primary key can be defined via primaryKey() which defaults to id if not specified.

The following is an example model called Customer:

class Customer extends \yii\redis\ActiveRecord
{
    public function attributes()
    {
        return ['id', 'name', 'address', 'registration_date'];
    }
}

Public Methods

Hide inherited methods

Method Description Defined By
attributes() Returns the list of all attribute names of the model. yii\redis\ActiveRecord
buildKey() Builds a normalized key from a given primary key value. yii\redis\ActiveRecord
deleteAll() Deletes rows in the table using the provided conditions. yii\redis\ActiveRecord
find() yii\redis\ActiveRecord
getDb() Returns the database connection used by this AR class. yii\redis\ActiveRecord
insert() yii\redis\ActiveRecord
keyPrefix() Declares prefix of the key that represents the keys that store this records in redis. yii\redis\ActiveRecord
primaryKey() Returns the primary key name(s) for this AR class. yii\redis\ActiveRecord
updateAll() Updates the whole table using the provided attribute values and conditions. yii\redis\ActiveRecord
updateAllCounters() Updates the whole table using the provided counter changes and conditions. yii\redis\ActiveRecord

Method Details

Hide inherited methods

attributes() public method

Returns the list of all attribute names of the model.

This method must be overridden by child classes to define available attributes.

public array attributes ( )
return array

List of attribute names.

                public function attributes()
{
    throw new InvalidConfigException('The attributes() method of redis ActiveRecord has to be implemented by child classes.');
}

            
buildKey() public static method

Builds a normalized key from a given primary key value.

public static string buildKey ( $key )
$key mixed

The key to be normalized

return string

The generated key

                public static function buildKey($key)
{
    if (is_numeric($key)) {
        return $key;
    }
    if (is_string($key)) {
        return ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
    }
    if (is_array($key)) {
        if (count($key) == 1) {
            return self::buildKey(reset($key));
        }
        ksort($key); // ensure order is always the same
        $isNumeric = true;
        foreach ($key as $value) {
            if (!is_numeric($value)) {
                $isNumeric = false;
            }
        }
        if ($isNumeric) {
            return implode('-', $key);
        }
    }
    return md5(json_encode($key, JSON_NUMERIC_CHECK));
}

            
deleteAll() public static method

Deletes rows in the table using the provided conditions.

WARNING: If you do not specify any condition, this method will delete ALL rows in the table.

For example, to delete all customers whose status is 3:

Customer::deleteAll(['status' => 3]);
public static integer deleteAll ( $condition null )
$condition array

The conditions that will be put in the WHERE part of the DELETE SQL. Please refer to ActiveQuery::where() on how to specify this parameter.

return integer

The number of rows deleted

                public static function deleteAll($condition = null)
{
    $pks = self::fetchPks($condition);
    if (empty($pks)) {
        return 0;
    }
    $db = static::getDb();
    $attributeKeys = [];
    $db->executeCommand('MULTI');
    foreach ($pks as $pk) {
        $pk = static::buildKey($pk);
        $db->executeCommand('LREM', [static::keyPrefix(), 0, $pk]);
        $attributeKeys[] = static::keyPrefix() . ':a:' . $pk;
    }
    $db->executeCommand('DEL', $attributeKeys);
    $result = $db->executeCommand('EXEC');
    return end($result);
}

            
find() public static method

public static yii\redis\ActiveQuery find ( )
return yii\redis\ActiveQuery

The newly created yii\redis\ActiveQuery instance.

                public static function find()
{
    return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
}

            
getDb() public static method

Returns the database connection used by this AR class.

By default, the "redis" application component is used as the database connection. You may override this method if you want to use a different database connection.

public static yii\redis\Connection getDb ( )
return yii\redis\Connection

The database connection used by this AR class.

                public static function getDb()
{
    return Yii::$app->get('redis');
}

            
insert() public method

public void insert ( $runValidation true, $attributes null )
$runValidation
$attributes

                public function insert($runValidation = true, $attributes = null)
{
    if ($runValidation && !$this->validate($attributes)) {
        return false;
    }
    if (!$this->beforeSave(true)) {
        return false;
    }
    $db = static::getDb();
    $values = $this->getDirtyAttributes($attributes);
    $pk = [];
    foreach (static::primaryKey() as $key) {
        $pk[$key] = $values[$key] = $this->getAttribute($key);
        if ($pk[$key] === null) {
            // use auto increment if pk is null
            $pk[$key] = $values[$key] = $db->executeCommand('INCR', [static::keyPrefix() . ':s:' . $key]);
            $this->setAttribute($key, $values[$key]);
        } elseif (is_numeric($pk[$key])) {
            // if pk is numeric update auto increment value
            $currentPk = $db->executeCommand('GET', [static::keyPrefix() . ':s:' . $key]);
            if ($pk[$key] > $currentPk) {
                $db->executeCommand('SET', [static::keyPrefix() . ':s:' . $key, $pk[$key]]);
            }
        }
    }
    // save pk in a findall pool
    $pk = static::buildKey($pk);
    $db->executeCommand('RPUSH', [static::keyPrefix(), $pk]);
    $key = static::keyPrefix() . ':a:' . $pk;
    // save attributes
    $setArgs = [$key];
    foreach ($values as $attribute => $value) {
        // only insert attributes that are not null
        if ($value !== null) {
            if (is_bool($value)) {
                $value = (int) $value;
            }
            $setArgs[] = $attribute;
            $setArgs[] = $value;
        }
    }
    if (count($setArgs) > 1) {
        $db->executeCommand('HMSET', $setArgs);
    }
    $changedAttributes = array_fill_keys(array_keys($values), null);
    $this->setOldAttributes($values);
    $this->afterSave(true, $changedAttributes);
    return true;
}

            
keyPrefix() public static method

Declares prefix of the key that represents the keys that store this records in redis.

By default this method returns the class name as the table name by calling Inflector::camel2id(). For example, 'Customer' becomes 'customer', and 'OrderItem' becomes 'order_item'. You may override this method if you want different key naming.

public static string keyPrefix ( )
return string

The prefix to apply to all AR keys

                public static function keyPrefix()
{
    return Inflector::camel2id(StringHelper::basename(get_called_class()), '_');
}

            
primaryKey() public static method

Returns the primary key name(s) for this AR class.

This method should be overridden by child classes to define the primary key.

Note that an array should be returned even when it is a single primary key.

public static string[] primaryKey ( )
return string[]

The primary keys of this record.

                public static function primaryKey()
{
    return ['id'];
}

            
updateAll() public static method

Updates the whole table using the provided attribute values and conditions.

For example, to change the status to be 1 for all customers whose status is 2:

Customer::updateAll(['status' => 1], ['id' => 2]);
public static integer updateAll ( $attributes, $condition null )
$attributes array

Attribute values (name-value pairs) to be saved into the table

$condition array

The conditions that will be put in the WHERE part of the UPDATE SQL. Please refer to ActiveQuery::where() on how to specify this parameter.

return integer

The number of rows updated

                public static function updateAll($attributes, $condition = null)
{
    if (empty($attributes)) {
        return 0;
    }
    $db = static::getDb();
    $n = 0;
    foreach (self::fetchPks($condition) as $pk) {
        $newPk = $pk;
        $pk = static::buildKey($pk);
        $key = static::keyPrefix() . ':a:' . $pk;
        // save attributes
        $delArgs = [$key];
        $setArgs = [$key];
        foreach ($attributes as $attribute => $value) {
            if (isset($newPk[$attribute])) {
                $newPk[$attribute] = $value;
            }
            if ($value !== null) {
                if (is_bool($value)) {
                    $value = (int) $value;
                }
                $setArgs[] = $attribute;
                $setArgs[] = $value;
            } else {
                $delArgs[] = $attribute;
            }
        }
        $newPk = static::buildKey($newPk);
        $newKey = static::keyPrefix() . ':a:' . $newPk;
        // rename index if pk changed
        if ($newPk != $pk) {
            $db->executeCommand('MULTI');
            if (count($setArgs) > 1) {
                $db->executeCommand('HMSET', $setArgs);
            }
            if (count($delArgs) > 1) {
                $db->executeCommand('HDEL', $delArgs);
            }
            $db->executeCommand('LINSERT', [static::keyPrefix(), 'AFTER', $pk, $newPk]);
            $db->executeCommand('LREM', [static::keyPrefix(), 0, $pk]);
            $db->executeCommand('RENAME', [$key, $newKey]);
            $db->executeCommand('EXEC');
        } else {
            if (count($setArgs) > 1) {
                $db->executeCommand('HMSET', $setArgs);
            }
            if (count($delArgs) > 1) {
                $db->executeCommand('HDEL', $delArgs);
            }
        }
        $n++;
    }
    return $n;
}

            
updateAllCounters() public static method

Updates the whole table using the provided counter changes and conditions.

For example, to increment all customers' age by 1,

Customer::updateAllCounters(['age' => 1]);
public static integer updateAllCounters ( $counters, $condition null )
$counters array

The counters to be updated (attribute name => increment value). Use negative values if you want to decrement the counters.

$condition array

The conditions that will be put in the WHERE part of the UPDATE SQL. Please refer to ActiveQuery::where() on how to specify this parameter.

return integer

The number of rows updated

                public static function updateAllCounters($counters, $condition = null)
{
    if (empty($counters)) {
        return 0;
    }
    $db = static::getDb();
    $n = 0;
    foreach (self::fetchPks($condition) as $pk) {
        $key = static::keyPrefix() . ':a:' . static::buildKey($pk);
        foreach ($counters as $attribute => $value) {
            $db->executeCommand('HINCRBY', [$key, $attribute, $value]);
        }
        $n++;
    }
    return $n;
}