salibhdr/typhoon-cache

一个用于自动缓存记录和路由响应的Laravel包,只需设置少量配置即可

v1.0 2019-10-13 06:02 UTC

This package is auto-updated.

Last update: 2024-09-04 20:54:59 UTC


README

Salibhdr|typhoon

Total Downloads Latest Stable Version Latest Unstable Version License

简介

Typhoon Cache是一个Laravel包,只需少量设置即可自动添加和检索缓存数据。Typhoon Cache使用您的默认缓存存储来存储缓存数据。建议使用Redis和Memcache。

本包中可用的缓存方法

  1. Eloquent模型缓存:缓存模型数据
  2. 路由缓存:缓存带有响应数据的路由

安装

使用Composer安装

 $ composer require salibhdr/typhoon-cache

入门指南

Laravel

配置文件(必需)

安装Typhoon Cache库后,在config/app.php配置文件中注册SaliBhdr\TyphoonCache\ServiceProviders\TyphoonCacheServiceProvider::class

'providers' => [

     // Other service providers...
     
     SaliBhdr\TyphoonCache\ServiceProviders\TyphoonCacheServiceProvider::class,
],

使用发布命令将包配置复制到本地config

php artisan vendor:publish --provider="SaliBhdr\TyphoonCache\ServiceProviders\TyphoonCacheServiceProvider"
Lumen

在bootstrap/app.php中注册服务提供者

$app->register(SaliBhdr\TyphoonCache\ServiceProviders\TyphoonCacheServiceProvider::class);

将目录/vendor/salibhdr/typhoon-cache/config中的typhoon-cache.php配置文件手动复制到目录/config(您可能需要创建此目录)

在bootstrap/app.php中注册配置文件

$app->configure('typhoon-cache')

配置

配置文件示例
// typhoon-cache.php :

return [
    'cache-method' => \SaliBhdr\TyphoonCache\TyphoonCache::dispatcherEventMethod, // dispatcher,observer (change it to observer if you have another observer trait like laravel scout)
    'default-cache-ttl' => 60,// Defaults to 1 hour. in minutes || if (null)->default or (-1)->forever
    'is_cache_active' => true,
    'models' => [
        //model namespace
        App\Book::class => [
            'cache_key' => 'book', //if (null)-> sets model class name
            'cache-ttl' => 60, // Defaults to 1 hour. in minutes || if (null)->default or (-1)->forever
            'is_cache_active' => true, // true,false
            'is_based_on_user' => true, //true,false
            'cache-on' => [
                'retrieved' => false,
                'created' => false,
                'updated' => false,
                'saved' => true,
                'restored' => false,
            ],
            'delete-on' => [
                'deleted' => true,
            ],
        ],
    ],

    'routes' => [
        'api/v1/books' => [
            'is_cache_active' => true, // true,false
            'cache-ttl' => 60, // Defaults to 1 hour. in minutes || if (null)->default or (-1)->forever
            'is_based_on_user' => false, //true,false
            'prefix' => ''
        ],
    ]
];
配置文件说明

Typhoon缓存配置选项

  1. cache-method(字符串):有2个选项
    1. dispatcher:使用模型$dispatcherEvents来处理事件。如果您在模型中还有其他EventDispatcher事件,请使用观察者模式
    2. observer:注册一个观察者来观察模型事件。如果您在模型中还有其他使用模型观察者的特性,如Laravel Scout,请使用分发器方法
  2. default-cache-ttl(整数):缓存有效期(分钟)。如果没有在模型或路由中指定缓存有效期,则使用此默认有效期
  3. is_cache_active(布尔值):激活和停用所有缓存
  4. models(数组):将要使用缓存的模型数组
    1. 使用类命名空间作为数组键('App\Book'或App\Book::class)
    2. cache_key(字符串):将要添加到缓存存储中的缓存键,如果设置为null,则使用模型的表名
    3. cache-ttl(整数):模型缓存有效期(分钟)
    4. is_cache_active(布尔值):仅激活和停用指定的模型缓存
    5. is_based_on_user(布尔值):如果模型数据在不同用户之间存在差异,请设置为true。
    6. cache-on(数组):要缓存的模型事件数组。以下是模型事件的列表
    7. delete-on(数组):要删除缓存的模型事件数组
  5. routes(数组):将要使用缓存的路线数组
    1. 使用应用基本URL后的完整URL,不要在URL前加斜杠(正确方式:api/v1/books),(错误方式:example.com/api/v1/books),(错误方式:/api/v1/books)
    2. is_cache_active(布尔值):仅激活和停用指定的路由缓存
    3. cache-ttl(布尔值):路由缓存有效期(分钟)
    4. is_based_on_user(布尔值):如果路由数据在不同用户之间存在差异,请设置为true。
    5. prefix(字符串):如果您想为路由缓存键添加键前缀

提示:如果将模型或路由中的缓存有效期设置为null,则使用默认有效期。

提示2:如果将默认缓存有效期设置为null,则将其设置为默认60。

提示3:如果您将任何缓存有效期设置为-1,则缓存数据将永远存在,直到再次刷新

用法

1)Eloquent模型缓存

台风缓存使用优雅的模型事件来添加、更新、删除和检索数据。如果您想了解更多关于Laravel模型事件的信息,请点击这里

可用的Laravel模型事件

来自Laravel文档

检索事件将在从数据库检索现有模型时触发。当新模型首次保存时,将触发创建和创建事件。如果模型已经在数据库中存在并且调用了保存方法,将触发更新/更新事件。然而,在这两种情况下,都会触发保存/已保存事件。

通过使用这些事件,台风缓存将缓存模型数据。

首先在您希望缓存的模型中使用CacheableModel特质

    namespace App;

    use Illuminate\Database\Eloquent\Model
    use SaliBhdr\TyphoonCache\CacheableModel;

    class Book extends Model
    {
        use CacheableModel;
    }

根据配置文件,将您希望缓存的模型添加到models数组中作为数组键

 // typhoon-cache.php

'models' => [
       //model namespace
       App\Book::class => [...],
       App\Category::class => [...],
       App\User::class => [...],
   ],

在类的每个数组中,我们都有cached-on和delete-on方法。您必须将您想要缓存的任何事件添加到cached-on数组中,并且如果您想在任何事件中删除缓存,只需将该事件添加到delete-on数组中。我建议您只在delete-on数组中添加deleted和forceDeleted。

 // typhoon-cache.php

App\Book::class => [
           'cache_key' => 'book',
           'cache-ttl' => 60, 
           'is_cache_active' => true, 
           'is_based_on_user' => true, 
           'cache-on' => [
               'retrieved' => false,
               'created' => false,
               'updated' => false,
               'saved' => true,
               'restored' => false,
           ],
           'delete-on' => [
               'deleted' => true,
           ],
       ],

注意:尽量避免与保存事件一起使用created或updated事件,因为在创建或更新记录时,保存和保存事件也会触发,这样数据将缓存两次。使用保存方法缓存数据的优点是它还会在缓存存储中保存模型关系。

注意2:有两种缓存方式。

  1. 在数据创建或更新时

    此方法的优点

    • 检索数据快,因为数据检索时不会浪费在缓存上
    • 数据始终是最新的,因为每次更新数据时,缓存都会刷新

    此方法的缺点

    • 可能会缓存永远不会使用的数据,从而占用缓存存储空间
  2. 当数据被检索时

方法1将看起来像这样

// typhoon-cache.php

App\Book::class => [
           'cache-on' => [
               'retrieved' => true,
           ],
           'delete-on' => [
               'deleted' => true,
           ],
       ],

方法2将看起来像这样

// typhoon-cache.php

App\Book::class => [
           'cache-on' => [
               'saved' => true,
           ],
           'delete-on' => [
               'deleted' => true,
           ],
       ],

此方法的优点

  • 更新和创建记录将很快
  • 缓存从未使用的数据的机会较低

此方法的缺点

  • 数据可能会过时
  • 由于缓存过程,检索数据可能会变慢

但您可以自由地以任何您喜欢的的方式来缓存模型数据。

如果模型使用软删除,请勿忘记在delete-on数组中添加forceDeleted事件,并在cache-on数组中添加restored

// typhoon-cache.php

// If model uses softdelete
App\Book::class => [
           'cache-on' => [
               'saved' => true,
               'resotred' => true
           ],
           'delete-on' => [
               'forceDeleted' => true,
               'deleted' => true,
           ],
       ],

您还可以在模型中指定模型配置,这样就不需要在配置文件中添加它

// App\Book.php

  /**
   * gets related cache config for model
   *
   * @return array
   */
  protected function getCacheModelConfig()
  {
      return [
              'cache_key' => 'book', 
              'cache-ttl' => 60, 
              'is_cache_active' => true, 
              'is_based_on_user' => true,
                   'cache-on' => [
                       'saved' => true,
                   ],
                   'delete-on' => [
                       'deleted' => true,
                   ],
               ];
  }

台风缓存将整个模型对象缓存到缓存存储中,但如果您只想缓存一些属性,可以自由地在toCacheable()方法中指定可缓存的数据,但这不是必需的。台风缓存将自动完成所有繁重的工作

// App\Book.php
      /**
       * if you want to customize what you want to cache just override this method
       *
       * @return Model
       */
      public function toCacheable()
      {
      
      // method 1
        return $this;
        
      // method 2
        return $this->toArray(); 
        
      // method 3
          return [
            'title' => $this->title
            'author' => $this->author
          ]; // returns data only with these two attributes
      }

您可以使用isCachedData()方法检查您检索的数据是否是缓存数据还是数据库数据

// In controller


      // if you want 1 record
      public function getBook(Request $request) 
      {
       $book = Book::findOrFail($request->get('book_id'));
       
       dd($book->isCachedData()); // returns true if its cached data
      }
      
      //if you want multipul records 
      public function getBooks(Request $request) 
      {
       $books = Book::get();
       
       foreach($books as $book)
          dd($book->isCachedData()); // returns true if its cached data
      }

您可以使用retrieveModel()直接从缓存存储中检索数据

// In controller

use SaliBhdr\TyphoonCache\Facades\TyphoonCache
use App\Book

      public function getBook(Request $request) 
      {
      
       // first parametr is the model that you the data is related to.
       // second argument is the records id 
       // third argument (optional) : if is_based_on_user option in config file is set to true
       
         $book = TyphoonCache::retrieveModel(Book::class,$request->get('book_id'),auth()->id());
       
       
       dd($book->isCachedData()); // returns true if its cached data
      }
       

2) 路由缓存

此方法仅在数据被请求一次时缓存数据。它必须仅用于将要获取一些数据的路由,而不是用于更新数据或创建。因为这是一个在http级别的缓存方法,请求永远不会进入控制器。

在配置文件中指定您想要缓存的路由

// typhoon-cache.php :

return [
    'routes' => [
        'api/v1/books' => [
            'is_cache_active' => true, 
            'cache-ttl' => 60, 
            'is_based_on_user' => true,
            'prefix' => ''
        ],
    ]
];

就是这样。数据将根据您在配置文件中指定的设置自动缓存和检索。

有关路由配置的更多解释,请参阅上面的配置解释部分。

待办事项

  • 编写测试
  • 添加更有效的模型数据检索
  • 在readme中添加检索缓存方法

许可证

Typhoon-Cache是在MIT许可证下发布的。

用❤为您打造。

免费软件,太棒了!

贡献

贡献、有用的评论和反馈非常受欢迎!