定制 devgroup/yii2-tag-dependency-helper 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

devgroup/yii2-tag-dependency-helper

Composer 安装命令:

composer require devgroup/yii2-tag-dependency-helper

包简介

Helper for unifying cache tag names with invalidation support in yii2

关键字:

README 文档

README

Latest Stable Version Total Downloads Latest Unstable Version License Code Climate Scrutinizer Code Quality Build Status

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

Installation

The preferred way to install this extension is through composer.

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

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

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

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

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 is a technique inspired by 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

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

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

  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. Check out our another open-source projects!

devgroup/yii2-tag-dependency-helper 适用场景与选型建议

devgroup/yii2-tag-dependency-helper 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 532.68k 次下载、GitHub Stars 达 32, 最近一次更新时间为 2014 年 11 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「cache」 「yii2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 devgroup/yii2-tag-dependency-helper 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 devgroup/yii2-tag-dependency-helper 我们能提供哪些服务?
定制开发 / 二次开发

基于 devgroup/yii2-tag-dependency-helper 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 532.68k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 34
  • 点击次数: 29
  • 依赖项目数: 19
  • 推荐数: 0

GitHub 信息

  • Stars: 32
  • Watchers: 18
  • Forks: 16
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2014-11-24