项目作者: alex433

项目描述 :
Laravel's Eloquent models caching
高级语言: PHP
项目地址: git://github.com/alex433/laravel-eloquent-cache.git
创建时间: 2019-03-01T13:02:01Z
项目社区:https://github.com/alex433/laravel-eloquent-cache

开源协议:MIT License

下载


Laravel Eloquent cache

Total Downloads
Latest Stable Version
Latest Unstable Version
License

Laravel’s Eloquent models caching

Installation

Install via composer :

composer require alex433/laravel-eloquent-cache

How it works

When Eloquent fetches models by primary key, the SQL query result are cached.
Subsequently, when eloquent fetches a model by primary key, the cached result will be used.
The cache entry will be flushed when you create, update, or delete a model instance.

Usage

Use the Cachable trait in the models you want to cache.

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Alex433\LaravelEloquentCache\Cachable;
  5. class Post extends Model
  6. {
  7. use Cachable;
  8. }

In next cases cache queries will be executed instead SQL queries. Also it do the trick for “belongs To” relations.

  1. Post::find($id); // findOrFail(), findOrNew()
  2. Post::where('id', $id)->first(); // firstOrFail(), firstOrNew(), firstOrCreate(), firstOr()
  3. Post::whereId($id)->first();
  4. Post::where('id', $id)->get();

You can optionally define the following properties to change default trait behavior.

  1. <?php
  2. namespace App;
  3. use Illuminate\Notifications\Notifiable;
  4. use Illuminate\Foundation\Auth\User as Authenticatable;
  5. use Alex433\LaravelEloquentCache\Cachable;
  6. class User extends Authenticatable
  7. {
  8. use Notifiable,
  9. Cachable;
  10. /**
  11. * Cache TTL in seconds. Defaults indefinitely
  12. *
  13. * @var int $cacheTtl
  14. */
  15. public $cacheTtl = 3600;
  16. /**
  17. * Cache store name. Defaults default cache connection
  18. *
  19. * @var string $cacheStore
  20. */
  21. public $cacheStore = 'redis';
  22. /**
  23. * Cache tags. Defaults no tags
  24. *
  25. * @var array $cacheTags
  26. */
  27. public $cacheTags = ['users'];
  28. }

To invalidate the cache entry for a model instance, use forget method.

  1. User::find($id)->forget();
  2. // or
  3. User::find($id)->forget()->refresh();

When cache tags is used, you can flush the cache for a model, use the flushCache method.

  1. User::flushCache();
  2. // or
  3. User::find($id)->flushCache();