PHPackages                             devgroup/yii2-tag-dependency-helper - 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. devgroup/yii2-tag-dependency-helper

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

devgroup/yii2-tag-dependency-helper
===================================

Helper for unifying cache tag names with invalidation support in yii2

1.5.0(9y ago)34507.4k↓20.4%167MITPHPPHP &gt;=5.5.0

Since Nov 24Pushed 8y ago18 watchersCompare

[ Source](https://github.com/DevGroup-ru/yii2-tag-dependency-helper)[ Packagist](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)[ RSS](/packages/devgroup-yii2-tag-dependency-helper/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (3)Versions (11)Used By (7)

yii2-tag-dependency-helper
==========================

[](#yii2-tag-dependency-helper)

[![Latest Stable Version](https://camo.githubusercontent.com/ab61a545b6f929f7e5f669a2692872e216fb9bdcd391bea9c05c4802dc9f62ff/68747470733a2f2f706f7365722e707567782e6f72672f64657667726f75702f796969322d7461672d646570656e64656e63792d68656c7065722f762f737461626c65)](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)[![Total Downloads](https://camo.githubusercontent.com/b122995b9eb69f7eb54ff0c59f326cc88a3d3b6beeb4ae64127dac76ebd0b35d/68747470733a2f2f706f7365722e707567782e6f72672f64657667726f75702f796969322d7461672d646570656e64656e63792d68656c7065722f646f776e6c6f616473)](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)[![Latest Unstable Version](https://camo.githubusercontent.com/7ea7d44b36e1fb6a2946a79e76c84ff7cb8d762725e78d71df66f8e4957dce10/68747470733a2f2f706f7365722e707567782e6f72672f64657667726f75702f796969322d7461672d646570656e64656e63792d68656c7065722f762f756e737461626c65)](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)[![License](https://camo.githubusercontent.com/e18ef20b8a79784deba2b74dc95b2bbc7eecbdb63ab70cf6acac7b1db0480288/68747470733a2f2f706f7365722e707567782e6f72672f64657667726f75702f796969322d7461672d646570656e64656e63792d68656c7065722f6c6963656e7365)](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)[![Code Climate](https://camo.githubusercontent.com/489e44fc41f38b377843fca8bfef332643d1261670f434fea0d5c281f809c95e/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f44657647726f75702d72752f796969322d7461672d646570656e64656e63792d68656c7065722f6261646765732f6770612e737667)](https://codeclimate.com/github/DevGroup-ru/yii2-tag-dependency-helper)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/12e22b654dbdd1d0b41032790f45d11309209b22e160d83563872d8d19be484c/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f44657647726f75702d72752f796969322d7461672d646570656e64656e63792d68656c7065722f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/DevGroup-ru/yii2-tag-dependency-helper/?branch=master)[![Build Status](https://camo.githubusercontent.com/60682d071a8b31419c3977e4cca09a8c5db3bc3f6a34d1194670ae8fb1a8b242/68747470733a2f2f7472617669732d63692e6f72672f44657647726f75702d72752f796969322d7461672d646570656e64656e63792d68656c7065722e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/DevGroup-ru/yii2-tag-dependency-helper)

Helper for unifying cache tag names with invalidation support for Yii2 ActiveRecord models.

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

[](#installation)

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

Either run

```
php composer.phar require --prefer-dist devgroup/yii2-tag-dependency-helper "*"

```

or add

```
"devgroup/yii2-tag-dependency-helper": "*"

```

to the require section of your `composer.json` file.

Core concept
------------

[](#core-concept)

This extension introduces 2 standard cache tags types for ActiveRecord:

- common tag - Tag is invalidated if any model of this type is updated/inserted
- object tag - Tag is invalidated if exact model record is updated(ie. Product with id=2)
- composite tag - Tag is invalidated if model with specified fields record is updated

Usage
-----

[](#usage)

In your active record model add behavior and trait:

```
use \DevGroup\TagDependencyHelper\TagDependencyTrait;

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'CacheableActiveRecord' => [
            'class' => \DevGroup\TagDependencyHelper\CacheableActiveRecord::className(),
        ],
    ];
}
```

This behavior automatically invalidates tags by model name and pair model-id.

### Finding model

[](#finding-model)

There's a special method in TagDependencyTrait for finding models by ID with using tag cache:

```
/**
 * Finds or creates new model using or not using cache(objectTag is applied, not commonTag!)
 * @param string|int $id ID of model to find
 * @param bool $createIfEmptyId Create new model instance(record) if id is empty
 * @param bool $useCache Use cache
 * @param int $cacheLifetime Cache lifetime in seconds
 * @param bool|\Exception $throwException False or exception instance to throw if model not found or (empty id AND createIfEmptyId==false)
 * @return \yii\db\ActiveRecord|null|self|TagDependencyTrait
 * @throws \Exception
 */
public static function loadModel(
    $id,
    $createIfEmptyId = false,
    $useCache = true,
    $cacheLifetime = 86400,
    $throwException = false
)
{
}
```

Example call: `$post = Post::loadModel('', false, false, 0, new \Exception("test2"));`

For Post model instance(`$post`) cache will be automatically invalidated by object and common tags on update,insert,delete.

Direct invalidation can be done by calling `$post->invalidateTags()`.

### Adding cache tags in other scenarios

[](#adding-cache-tags-in-other-scenarios)

If your cache entry should be flushed every time any row of model is edited - use `getCommonTag` helper function:

```
$models = Configurable::getDb()->cache(
    function ($db) {
        return Configurable::find()->all($db);
    },
    86400,
    new TagDependency([
        'tags' => NamingHelper::getCommonTag(Configurable::className()),
    ])
);
```

If your cache entry should be flushed only when exact row of model is edited - use `getObjectTag` helper function:

```
$cacheKey = 'Product:' . $model_id;
if (false === $product = Yii::$app->cache->get($cacheKey)) {
    if (null === $product = Product::findById($model_id)) {
        throw new NotFoundHttpException;
    }
    Yii::$app->cache->set(
        $cacheKey,
        $product,
        86400,
        new TagDependency(
            [
                'tags' => [
                    NamingHelper::getObjectTag(Product::className(), $model_id),
                ]
            ]
        )
    );
}
```

If your cache entry should be flushed only when row of model with specified fields is edited - use `getCompositeTag` helper function and override function `cacheCompositeTagFields` in model:

```
//in model for cache, in this case Comments model
protected function cacheCompositeTagFields()
{
    return ['id_app', 'object_table', 'id_object'];
}

//Data for caching
$comments = Comments::getDb()->cache(
    function ($db) use ($id_app, $id_object, $object_table) {
        return Comments::find()->where(['id_app' => $id_app, 'object_table' => $object_table, 'id_object' => $id_object])->all($db);
    },
    0,
    new TagDependency([
        'tags' => [
            NamingHelper::getCompositeTag(Comments::className(), ['id_app' => $id_app, 'object_table' => $object_table, 'id_object' => $id_object])
        ]
    ])
);

//PROFIT!
```

Lazy cache
----------

[](#lazy-cache)

Lazy cache is a technique inspired by [iiifx-production/yii2-lazy-cache](https://github.com/iiifx-production/yii2-lazy-cache) composer package.

After configuring(see below) you can use it like this:

```
$pages = Yii::$app->cache->lazy(function() {
    return Page::find()->where(['active'=>1])->all();
}, 'AllActivePages', 3600, $dependency);
```

In this example Pages find query will be performed only if cache entry with key `AllActivePages` will not be found. After successful retrieving of models array the result will be automatically stored in cache with `AllActivePages` as cache key for 3600 seconds and with `$dependency` as Cache dependency.

### Configuring - Performance-way

[](#configuring---performance-way)

For performance reasons(yii2 behaviors are slower then traits) - create your own `\yii\caching\Cache` class and add `LazyCacheTrait` to it, for example:

```
namespace app\components;

class MyCache extends \yii\caching\FileCache {
    use \DevGroup\TagDependencyHelper\LazyCacheTrait;
}
```

And modify your application configuration to use your cache component:

```
return [
    'components' => [
        'class' => '\app\components\MyCache',
    ],
];
```

Now you can use lazy cache:

### Configuring - Behavior-way

[](#configuring---behavior-way)

Just modify your configuration like this:

```
return [
    'components' => [
        'cache' => [
            'class' => '\yii\caching\FileCache',
            'as lazy' => [
                'class' => '\DevGroup\TagDependencyHelper\LazyCache',
            ],
        ],
    ],
];
```

Migrating from 0.0.x to 1.x
---------------------------

[](#migrating-from-00x-to-1x)

1. We have changed namespace from `devgroup` to `DevGroup`
2. We've splitted behavior into 3 components:

- CacheableActiveRecord - behavior that adds invalidation on update/insert/delete of ActiveRecord model
- TagDependencyTrait - trait that must be also added to ActiveRecord class, handles invalidation and adds new static method `loadModel`
- NamingHelper - the only one class that handles naming policy for cache tags

---

Brought to you by [DevGroup.ru](https://devgroup.ru/). Check out our another [open-source projects](https://github.com/DevGroup-ru)!

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity49

Moderate usage in the ecosystem

Community31

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 66.7% 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 ~72 days

Recently: every ~85 days

Total

10

Last Release

3544d ago

Major Versions

0.0.3 → 1.0.02015-09-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/19c9303caa5846f2500a35018dcbd3c7f07c74e30efc1bbf7878d54157ab9c4f?d=identicon)[bethrezen](/maintainers/bethrezen)

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

---

Top Contributors

[![bethrezen](https://avatars.githubusercontent.com/u/260284?v=4)](https://github.com/bethrezen "bethrezen (24 commits)")[![free6k](https://avatars.githubusercontent.com/u/1732637?v=4)](https://github.com/free6k "free6k (5 commits)")[![miramir](https://avatars.githubusercontent.com/u/686364?v=4)](https://github.com/miramir "miramir (2 commits)")[![Philosoft](https://avatars.githubusercontent.com/u/296326?v=4)](https://github.com/Philosoft "Philosoft (2 commits)")[![forecho](https://avatars.githubusercontent.com/u/1725326?v=4)](https://github.com/forecho "forecho (1 commits)")[![colinlear](https://avatars.githubusercontent.com/u/1740692?v=4)](https://github.com/colinlear "colinlear (1 commits)")[![DD174](https://avatars.githubusercontent.com/u/2971088?v=4)](https://github.com/DD174 "DD174 (1 commits)")

---

Tags

cachecache-controlhelperinvalidation-supportyii2yii2-cacheyii2-extensioncacheyii2

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/devgroup-yii2-tag-dependency-helper/health.svg)

```
[![Health](https://phpackages.com/badges/devgroup-yii2-tag-dependency-helper/health.svg)](https://phpackages.com/packages/devgroup-yii2-tag-dependency-helper)
```

###  Alternatives

[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)
