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

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

factorenergia/yii2-tag-dependency-helper
========================================

Helper for unifying cache tag names with invalidation support in yii2

1.5.0(9y ago)04.6k↓50%1MITPHPPHP &gt;=5.5.0

Since Nov 24Pushed 8y agoCompare

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

READMEChangelogDependencies (3)Versions (11)Used By (1)

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

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

[![Latest Stable Version](https://camo.githubusercontent.com/75793f9ad36953cfa2e3c4ffb73c72cea09b24d012e89980a53386c05dc1b38d/68747470733a2f2f706f7365722e707567782e6f72672f666163746f72656e65726769612f796969322d7461672d646570656e64656e63792d68656c7065722f762f737461626c65)](https://packagist.org/packages/factorenergia/yii2-tag-dependency-helper)[![Total Downloads](https://camo.githubusercontent.com/3dbf7f5edbe57db36deb6596d3429ebc19ac1a8ab2ee1945eae54ba902ffeb88/68747470733a2f2f706f7365722e707567782e6f72672f666163746f72656e65726769612f796969322d7461672d646570656e64656e63792d68656c7065722f646f776e6c6f616473)](https://packagist.org/packages/factorenergia/yii2-tag-dependency-helper)[![Latest Unstable Version](https://camo.githubusercontent.com/4e6731ee37aa5abc6933a673c6f72d8c050302afd62a913b0a5987b9d9ba3184/68747470733a2f2f706f7365722e707567782e6f72672f666163746f72656e65726769612f796969322d7461672d646570656e64656e63792d68656c7065722f762f756e737461626c65)](https://packagist.org/packages/factorenergia/yii2-tag-dependency-helper)[![License](https://camo.githubusercontent.com/a084b515de41d5c540d58c423f24c3a242a234984312866a13298c6cc496241c/68747470733a2f2f706f7365722e707567782e6f72672f666163746f72656e65726769612f796969322d7461672d646570656e64656e63792d68656c7065722f6c6963656e7365)](https://packagist.org/packages/factorenergia/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 factorenergia/yii2-tag-dependency-helper "*"

```

or add

```
"factorenergia/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 \factorenergia\TagDependencyHelper\TagDependencyTrait;

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'CacheableActiveRecord' => [
            'class' => \factorenergia\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 \factorenergia\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' => '\factorenergia\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/factorenergia)!

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 63.2% 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

3537d ago

Major Versions

0.0.3 → 1.0.02015-09-22

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/28297420?v=4)[Toni Huertas](/maintainers/factorenergia)[@factorenergia](https://github.com/factorenergia)

---

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)")[![jsvfactor](https://avatars.githubusercontent.com/u/22675432?v=4)](https://github.com/jsvfactor "jsvfactor (2 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)")[![DD174](https://avatars.githubusercontent.com/u/2971088?v=4)](https://github.com/DD174 "DD174 (1 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)")

---

Tags

cacheyii2

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[devgroup/yii2-tag-dependency-helper

Helper for unifying cache tag names with invalidation support in yii2

34507.4k7](/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)
