项目作者: jameslkingsley

项目描述 :
Easily cache items specific to your Eloquent models without having to append the ID.
高级语言: PHP
项目地址: git://github.com/jameslkingsley/laravel-scoped-cache.git
创建时间: 2019-05-09T08:35:16Z
项目社区:https://github.com/jameslkingsley/laravel-scoped-cache

开源协议:

下载


Model specific cache items made easy

This package adds a trait that provides a cache method for interacting with your app’s cache, but scoped to your Eloquent models. This removes the need to constantly append the model ID to your cache keys. Just access your cache like this instead $user->cache('Avatar').

Under the hood it will prefix your cache keys with a generated model-specific key, in the format Model_ID:your-key. You can completely override this format by implementing the getScopedCacheKey method on your model.

Installation

You can install the package via composer:

  1. composer require jameslkingsley/laravel-scoped-cache

Usage

Import the trait and use it on any Eloquent model. You can also use it on non-eloquent classes, providing they have a getKey method that returns their unique reference.

  1. use Kingsley\ScopedCache\ScopedCache;
  2. class User extends Model
  3. {
  4. use ScopedCache;
  5. }

Now you can use the cache how you would normally. You can set/get items directly from the cache method, or call any other cache method by leaving the argument list empty.

  1. $user->cache(['name' => $user->name], 5);
  2. $user->cache('name', 'default name');
  3. $user->cache()->remember('name', 5, function () {
  4. // $this refers to the model this cache instance is scoped to
  5. return $this->name;
  6. });

Keep in mind that this package is expecting the first argument of proxied calls to the cache to be the cache key. There might be some cases where custom macro’s break this format.