PHPackages                             devzyj/yii2-attribute-cache-behavior - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. devzyj/yii2-attribute-cache-behavior

ActiveYii2-extension[Caching](/categories/caching)

devzyj/yii2-attribute-cache-behavior
====================================

The ActiveRecord attribute cache behavior for Yii2.

1.0.1(7y ago)0261BSD-3-ClausePHP

Since Nov 2Pushed 7y ago1 watchersCompare

[ Source](https://github.com/devzyj/yii2-attribute-cache-behavior)[ Packagist](https://packagist.org/packages/devzyj/yii2-attribute-cache-behavior)[ RSS](/packages/devzyj-yii2-attribute-cache-behavior/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (2)Dependencies (2)Versions (3)Used By (0)

ActiveRecord attribute cache behavior
=====================================

[](#activerecord-attribute-cache-behavior)

提供了一些缓存 `ActiveRecord` 属性的方法。并且当某些事件发生时，自动使缓存失效。

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
composer require --prefer-dist "devzyj/yii2-attribute-cache-behavior" "~1.0.0"
```

or add

```
"devzyj/yii2-attribute-cache-behavior" : "~1.0.0"
```

to the require section of your application's `composer.json` file.

Usage
-----

[](#usage)

```
// User.php
class User extends \yii\db\ActiveRecord
{
    use \devzyj\behaviors\ActiveCacheBehaviorTrait;

    public function behaviors()
    {
        return [
            [
                'class' => 'devzyj\behaviors\ActiveCacheBehavior',
                //'cache' => 'cache',
                //'defaultDuration' => 604800,
                //'baseModelCacheKey' => ['User', 'PrimaryKey'],
                //'keyAttributes' => static::primaryKey(),
                //'valueAttributes' => $this->attributes(),
            ],
        ];
    }
}

// Using trait methods
// Returns a single active record model instance.
// Sets cache value if there is no cache available for the `$primaryKey`.
$user = User::findOrSetOneByAttribute($primaryKey);

// No changed, cache value exists.
$user->save();

// Changed, cache value not exists.
$user->name = 1;
$user->save();

// Deleted, cache value not exists.
$user->delete();

// Gets cache value for model instance.
$user->getActiveCache();

// Checks cache value exists for model instance.
$user->existsActiveCache();

// Sets cache value for model instance.
$user->setActiveCache();

// Adds cache value for model instance.
$user->addActiveCache();

// Deletes cache value for model instance.
$user->deleteActiveCache();

// Using single key attribute
// ActiveCacheBehavior::$keyAttributes = ['id']
$id = 1;

// get cache
User::instance()->getModelCacheByAttribute($id);
// OR
User::instance()->getModelCache(['id' => $id]);

// exists cache
User::instance()->existsModelCacheByAttribute($id);
// OR
User::instance()->existsModelCache(['id' => $id]);

// set cache
User::instance()->setModelCacheByAttribute($id, $value, $duration, $dependency);
// OR
User::instance()->setModelCache(['id' => $id], $value, $duration, $dependency);

// add cache
User::instance()->addModelCacheByAttribute($id, $value, $duration, $dependency);
// OR
User::instance()->addModelCache(['id' => $id], $value, $duration, $dependency);

// delete cache
User::instance()->deleteModelCacheByAttribute($id);
// OR
User::instance()->deleteModelCache(['id' => $id]);

// get or set cache
User::instance()->getOrSetModelCacheByAttribute($id, function ($behavior) use ($id) {
    $condition = $behavior->ensureActiveKeyAttribute($id);
    $model = User::findOne($condition);
    return $model ? $model->getActiveCacheValue() : false;
}, $duration, $dependency);
// OR
$condition = ['id' => $id];
User::instance()->getOrSetModelCache($condition, function ($behavior) use ($condition) {
    $model = User::findOne($condition);
    return $model ? $model->getActiveCacheValue() : false;
}, $duration, $dependency);

// trait method: find and return ActiveRecord from cache or database
User::findOrSetOneByAttribute($id, $duration, $dependency);

// Using composite key attribute
// ActiveCacheBehavior::$keyAttributes = ['id1', 'id2']
$id1 = 1;
$id2 = 2;
$ids = [$id1, $id2];

// get cache
User::instance()->getModelCacheByAttribute($ids);
// OR
User::instance()->getModelCache(['id1' => $id1, 'id2' => $id2]);

// exists cache
User::instance()->existsModelCacheByAttribute($ids);
// OR
User::instance()->existsModelCache(['id1' => $id1, 'id2' => $id2]);

// set cache
User::instance()->setModelCacheByAttribute($ids, $value, $duration, $dependency);
// OR
User::instance()->setModelCache(['id1' => $id1, 'id2' => $id2], $value, $duration, $dependency);

// add cache
User::instance()->addModelCacheByAttribute($ids, $value, $duration, $dependency);
// OR
User::instance()->addModelCache(['id1' => $id1, 'id2' => $id2], $value, $duration, $dependency);

// delete cache
User::instance()->deleteModelCacheByAttribute($ids);
// OR
User::instance()->deleteModelCache(['id1' => $id1, 'id2' => $id2]);

// get or set cache
User::instance()->getOrSetModelCacheByAttribute($ids, function ($behavior) use ($ids) {
    $condition = $behavior->ensureActiveKeyAttribute($ids);
    $model = User::findOne($condition);
    return $model ? $model->getActiveCacheValue() : false;
}, $duration, $dependency);
// OR
$condition = ['id1' => $id1, 'id2' => $id2];
User::instance()->getOrSetModelCache($condition, function ($behavior) use ($condition) {
    $model = User::findOne($condition);
    return $model ? $model->getActiveCacheValue() : false;
}, $duration, $dependency);

// trait method: find and return ActiveRecord from cache or database
User::findOrSetOneByAttribute($ids, $duration, $dependency);

// Using database transactions, and the `commit()` time is too long
$transaction = $db->beginTransaction();
try {
    // old cache key.
    $oldKey = $model->getActiveCacheKey();

    // update
    $model->attributes = $attributes;
    $model->save();
    $transaction->commit();

    // delete old cache.
    $model->deleteModelCache($oldKey);
} catch (\Exception $e) {
    $transaction->rollBack();
    throw $e;
}
```

###  Health Score

27

—

LowBetter than 47% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity7

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

2

Last Release

2795d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c88aa646d61c261caeccdb65d493c405562b7a4f052810a528ba8be399bec65e?d=identicon)[zhangyanjiong](/maintainers/zhangyanjiong)

---

Top Contributors

[![devzyj](https://avatars.githubusercontent.com/u/18346387?v=4)](https://github.com/devzyj "devzyj (16 commits)")

---

Tags

activerecordattributebehaviorcacheextensionyii2cacheyii2Behavioractiverecordattribute

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/devzyj-yii2-attribute-cache-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/devzyj-yii2-attribute-cache-behavior/health.svg)](https://phpackages.com/packages/devzyj-yii2-attribute-cache-behavior)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M3.0k](/packages/craftcms-cms)[devgroup/yii2-tag-dependency-helper

Helper for unifying cache tag names with invalidation support in yii2

34530.0k7](/packages/devgroup-yii2-tag-dependency-helper)[undefinedor/yii2-cached-active-record

The cached activeRecord for the Yii2 framework

102.6k](/packages/undefinedor-yii2-cached-active-record)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
