{"id":13411561,"url":"https://github.com/DevGroup-ru/yii2-tag-dependency-helper","last_synced_at":"2025-03-14T17:30:56.316Z","repository":{"id":23713204,"uuid":"27085791","full_name":"DevGroup-ru/yii2-tag-dependency-helper","owner":"DevGroup-ru","description":"Helper for unifying cache tag names with invalidation support in yii2","archived":false,"fork":false,"pushed_at":"2017-09-22T08:29:50.000Z","size":43,"stargazers_count":31,"open_issues_count":0,"forks_count":16,"subscribers_count":19,"default_branch":"master","last_synced_at":"2024-10-30T01:58:44.459Z","etag":null,"topics":["cache","cache-control","helper","invalidation-support","yii2","yii2-cache","yii2-extension"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DevGroup-ru.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2014-11-24T17:10:15.000Z","updated_at":"2023-08-08T14:02:55.000Z","dependencies_parsed_at":"2022-08-21T09:50:36.523Z","dependency_job_id":null,"html_url":"https://github.com/DevGroup-ru/yii2-tag-dependency-helper","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DevGroup-ru%2Fyii2-tag-dependency-helper","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DevGroup-ru%2Fyii2-tag-dependency-helper/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DevGroup-ru%2Fyii2-tag-dependency-helper/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DevGroup-ru%2Fyii2-tag-dependency-helper/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DevGroup-ru","download_url":"https://codeload.github.com/DevGroup-ru/yii2-tag-dependency-helper/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243618635,"owners_count":20320269,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cache","cache-control","helper","invalidation-support","yii2","yii2-cache","yii2-extension"],"created_at":"2024-07-30T20:01:14.541Z","updated_at":"2025-03-14T17:30:56.035Z","avatar_url":"https://github.com/DevGroup-ru.png","language":"PHP","funding_links":[],"categories":["Helpers 助手"],"sub_categories":[],"readme":"yii2-tag-dependency-helper\n==========================\n[![Latest Stable Version](https://poser.pugx.org/devgroup/yii2-tag-dependency-helper/v/stable)](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)\n[![Total Downloads](https://poser.pugx.org/devgroup/yii2-tag-dependency-helper/downloads)](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)\n[![Latest Unstable Version](https://poser.pugx.org/devgroup/yii2-tag-dependency-helper/v/unstable)](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)\n[![License](https://poser.pugx.org/devgroup/yii2-tag-dependency-helper/license)](https://packagist.org/packages/devgroup/yii2-tag-dependency-helper)\n[![Code Climate](https://codeclimate.com/github/DevGroup-ru/yii2-tag-dependency-helper/badges/gpa.svg)](https://codeclimate.com/github/DevGroup-ru/yii2-tag-dependency-helper)\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/DevGroup-ru/yii2-tag-dependency-helper/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/DevGroup-ru/yii2-tag-dependency-helper/?branch=master)\n[![Build Status](https://travis-ci.org/DevGroup-ru/yii2-tag-dependency-helper.svg?branch=master)](https://travis-ci.org/DevGroup-ru/yii2-tag-dependency-helper)\n\n\nHelper for unifying cache tag names with invalidation support for Yii2 ActiveRecord models.\n\n## Installation\n\nThe preferred way to install this extension is through [composer](http://getcomposer.org/download/).\n\nEither run\n\n```\nphp composer.phar require --prefer-dist devgroup/yii2-tag-dependency-helper \"*\"\n```\n\nor add\n\n```\n\"devgroup/yii2-tag-dependency-helper\": \"*\"\n```\n\nto the require section of your `composer.json` file.\n\n## Core concept\n\nThis extension introduces 2 standard cache tags types for ActiveRecord:\n- common tag - Tag is invalidated if any model of this type is updated/inserted\n- object tag - Tag is invalidated if exact model record is updated(ie. Product with id=2)\n- composite tag - Tag is invalidated if model with specified fields record is updated\n\n## Usage\n\nIn your active record model add behavior and trait:\n\n\n``` php\n\nuse \\DevGroup\\TagDependencyHelper\\TagDependencyTrait;\n\n/**\n * @inheritdoc\n */\npublic function behaviors()\n{\n    return [\n        'CacheableActiveRecord' =\u003e [\n            'class' =\u003e \\DevGroup\\TagDependencyHelper\\CacheableActiveRecord::className(),\n        ],\n    ];\n}\n\n```\n\nThis behavior automatically invalidates tags by model name and pair model-id.\n\n### Finding model\n\nThere's a special method in TagDependencyTrait for finding models by ID with using tag cache:\n\n```php\n/**\n * Finds or creates new model using or not using cache(objectTag is applied, not commonTag!)\n * @param string|int $id ID of model to find\n * @param bool $createIfEmptyId Create new model instance(record) if id is empty\n * @param bool $useCache Use cache\n * @param int $cacheLifetime Cache lifetime in seconds\n * @param bool|\\Exception $throwException False or exception instance to throw if model not found or (empty id AND createIfEmptyId==false)\n * @return \\yii\\db\\ActiveRecord|null|self|TagDependencyTrait\n * @throws \\Exception\n */\npublic static function loadModel(\n    $id,\n    $createIfEmptyId = false,\n    $useCache = true,\n    $cacheLifetime = 86400,\n    $throwException = false\n)\n{\n}\n```\n\nExample call: `$post = Post::loadModel('', false, false, 0, new \\Exception(\"test2\"));`\n\nFor Post model instance(`$post`) cache will be automatically invalidated by object and common tags on update,insert,delete.\n\nDirect invalidation can be done by calling `$post-\u003einvalidateTags()`.\n\n \n### Adding cache tags in other scenarios\n\nIf your cache entry should be flushed every time any row of model is edited - use `getCommonTag` helper function:\n\n``` php\n$models = Configurable::getDb()-\u003ecache(\n    function ($db) {\n        return Configurable::find()-\u003eall($db);\n    },\n    86400,\n    new TagDependency([\n        'tags' =\u003e NamingHelper::getCommonTag(Configurable::className()),\n    ])\n);\n```\n\nIf your cache entry should be flushed only when exact row of model is edited - use `getObjectTag` helper function:\n\n``` php\n$cacheKey = 'Product:' . $model_id;\nif (false === $product = Yii::$app-\u003ecache-\u003eget($cacheKey)) {\n    if (null === $product = Product::findById($model_id)) {\n        throw new NotFoundHttpException;\n    }\n    Yii::$app-\u003ecache-\u003eset(\n        $cacheKey,\n        $product,\n        86400,\n        new TagDependency(\n            [\n                'tags' =\u003e [\n                    NamingHelper::getObjectTag(Product::className(), $model_id),\n                ]\n            ]\n        )\n    );\n}\n\n```\n\nIf 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:\n\n``` php\n//in model for cache, in this case Comments model\nprotected function cacheCompositeTagFields()\n{\n    return ['id_app', 'object_table', 'id_object'];\n}\n\n//Data for caching\n$comments = Comments::getDb()-\u003ecache(\n    function ($db) use ($id_app, $id_object, $object_table) {\n        return Comments::find()-\u003ewhere(['id_app' =\u003e $id_app, 'object_table' =\u003e $object_table, 'id_object' =\u003e $id_object])-\u003eall($db);\n    },\n    0,\n    new TagDependency([\n        'tags' =\u003e [\n            NamingHelper::getCompositeTag(Comments::className(), ['id_app' =\u003e $id_app, 'object_table' =\u003e $object_table, 'id_object' =\u003e $id_object])\n        ]\n    ])\n);\n\n//PROFIT!\n```\n\n## Lazy cache\n\nLazy cache is a technique inspired by [iiifx-production/yii2-lazy-cache](https://github.com/iiifx-production/yii2-lazy-cache) composer package.\n\nAfter configuring(see below) you can use it like this:\n\n```php\n$pages = Yii::$app-\u003ecache-\u003elazy(function() {\n    return Page::find()-\u003ewhere(['active'=\u003e1])-\u003eall();\n}, 'AllActivePages', 3600, $dependency);\n```\n\nIn this example Pages find query will be performed only if cache entry with key `AllActivePages` will not be found.\nAfter successful retrieving of models array the result will be automatically stored in cache \nwith `AllActivePages` as cache key for 3600 seconds and with `$dependency` as Cache dependency.  \n\n### Configuring - Performance-way\n\nFor performance reasons(yii2 behaviors are slower then traits) - create your own `\\yii\\caching\\Cache` class\nand add `LazyCacheTrait` to it, for example:\n\n```php\nnamespace app\\components;\n\nclass MyCache extends \\yii\\caching\\FileCache {\n    use \\DevGroup\\TagDependencyHelper\\LazyCacheTrait;\n}\n```\n\nAnd modify your application configuration to use your cache component:\n\n```php\nreturn [\n    'components' =\u003e [\n        'class' =\u003e '\\app\\components\\MyCache',\n    ],\n];\n```\n\nNow you can use lazy cache:\n\n\n### Configuring - Behavior-way\n\nJust modify your configuration like this:\n\n```php\nreturn [\n    'components' =\u003e [\n        'cache' =\u003e [\n            'class' =\u003e '\\yii\\caching\\FileCache',\n            'as lazy' =\u003e [\n                'class' =\u003e '\\DevGroup\\TagDependencyHelper\\LazyCache',\n            ],\n        ],\n    ],\n];\n\n```\n\n## Migrating from 0.0.x to 1.x\n\n1. We have changed namespace from `devgroup` to `DevGroup`\n2. We've splitted behavior into 3 components:\n\n- CacheableActiveRecord - behavior that adds invalidation on update/insert/delete of ActiveRecord model\n- TagDependencyTrait - trait that must be also added to ActiveRecord class, handles invalidation and adds new static method `loadModel`\n- NamingHelper - the only one class that handles naming policy for cache tags\n\n---\n\nBrought to you by [DevGroup.ru](https://devgroup.ru/). Check out our another [open-source projects](https://github.com/DevGroup-ru)!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDevGroup-ru%2Fyii2-tag-dependency-helper","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDevGroup-ru%2Fyii2-tag-dependency-helper","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDevGroup-ru%2Fyii2-tag-dependency-helper/lists"}