codeat3/laravel-responsecache-php72

Spatie的laravel-responsecache分支版本,适用于PHP 7.2。通过缓存整个响应来加速Laravel应用程序

6.6.1 2020-03-05 20:44 UTC

README

Latest Version on Packagist MIT Licensed Build Status Quality Score Total Downloads

这是spatie的spatie优秀包laravel-responsecache的分支版本,但与PHP 7.2兼容。

此Laravel包可以缓存整个响应。默认情况下,它将缓存所有成功返回基于文本内容(如html和json)的get请求一周。这可能会大大加快响应速度。

因此,第一次请求时,包会保存响应然后再发送给用户。当相同的请求再次到来时,我们不会通过整个应用程序,而是直接响应已保存的响应。

Spatie是比利时的安特卫普的一家网页设计公司。您可以在他们的网站上找到所有开源项目的概述在这里

安装

您可以通过composer安装此包

composer require codeat3/laravel-responsecache-php72

包将自动注册自己。

您可以使用以下命令发布配置文件

php artisan vendor:publish --provider="Codeat3\ResponseCache\ResponseCacheServiceProvider"

这是发布配置文件的内容

// config/responsecache.php

return [
    /*
     * Determine if the response cache middleware should be enabled.
     */
    'enabled' => env('RESPONSE_CACHE_ENABLED', true),

    /*
     *  The given class will determinate if a request should be cached. The
     *  default class will cache all successful GET-requests.
     *
     *  You can provide your own class given that it implements the
     *  CacheProfile interface.
     */
    'cache_profile' => Codeat3\ResponseCache\CacheProfiles\CacheAllSuccessfulGetRequests::class,

    /*
     * When using the default CacheRequestFilter this setting controls the
     * default number of seconds responses must be cached.
     */
    'cache_lifetime_in_seconds' => env('RESPONSE_CACHE_LIFETIME', 60 * 24 * 7),

    /*
     * This setting determines if a http header named with the cache time
     * should be added to a cached response. This can be handy when
     * debugging.
     */
    'add_cache_time_header' => env('APP_DEBUG', true),

    /*
     * This setting determines the name of the http header that contains
     * the time at which the response was cached
     */
    'cache_time_header_name' => env('RESPONSE_CACHE_HEADER_NAME', 'laravel-responsecache'),

    /*
     * Here you may define the cache store that should be used to store
     * requests. This can be the name of any store that is
     * configured in app/config/cache.php
     */
    'cache_store' => env('RESPONSE_CACHE_DRIVER', 'file'),

    /*
     * Here you may define replacers that dynamically replace content from the response.
     * Each replacer must implement the Replacer interface.
     */
    'replacers' => [
        \Codeat3\ResponseCache\Replacers\CsrfTokenReplacer::class,
    ],

    /*
     * If the cache driver you configured supports tags, you may specify a tag name
     * here. All responses will be tagged. When clearing the responsecache only
     * items with that tag will be flushed.
     *
     * You may use a string or an array here.
     */
    'cache_tag' => '',

    /*
     * This class is responsible for generating a hash for a request. This hash
     * is used to look up an cached response.
     */
    'hasher' => \Codeat3\ResponseCache\Hasher\DefaultHasher::class,

    /*
     * This class serializes cache data and expands it.
     * Serialization can save the data to be returned in an appropriate form.
     */
    'serializer' => \Codeat3\ResponseCache\Serializer\DefaultSerializer::class,
];

最后,您应该在http内核中安装提供的中间件\Codeat3\ResponseCache\Middlewares\CacheResponse::class\Codeat3\ResponseCache\Middlewares\DoNotCacheResponse

// app/Http/Kernel.php

...

protected $middlewareGroups = [
   'web' => [
       ...
       \Codeat3\ResponseCache\Middlewares\CacheResponse::class,
   ],

...

protected $routeMiddleware = [
   ...
   'doNotCacheResponse' => \Codeat3\ResponseCache\Middlewares\DoNotCacheResponse::class,
];

用法

基本用法

默认情况下,包将缓存所有成功的get请求一周。登录用户将各自有自己的缓存。如果这是您需要的,您就完成了:安装ResponseCacheServerProvider就足够了。

清除缓存

手动清除

可以使用以下命令清除整个缓存

ResponseCache::clear();

这将清除在配置文件中指定的缓存存储中的所有内容。

使用控制台命令

可以通过运行以下Artisan命令完成相同操作

php artisan responsecache:clear

使用模型事件

您可以利用模型事件在模型保存或删除时清除缓存。以下是一个示例。

namespace App\Traits;

use Codeat3\ResponseCache\Facades\ResponseCache;

trait ClearsResponseCache
{
    public static function bootClearsResponseCache()
    {
        self::created(function () {
            ResponseCache::clear();
        });

        self::updated(function () {
            ResponseCache::clear();
        });

        self::deleted(function () {
            ResponseCache::clear();
        });
    }
}

忘记一个或多个特定的URI(s)

您可以使用以下方法忘记特定的URI

// Forget one URI
ResponseCache::forget('/some-uri');

// Forget several URIs
ResponseCache::forget(['/some-uri', '/other-uri']);

// Alternatively
ResponseCache::forget('/some-uri', '/other-uri');

forget方法仅在您在缓存配置文件中未使用cacheNameSuffix时才有效。

阻止请求被缓存

可以使用doNotCacheResponse中间件忽略请求。此中间件可以分配给路由和控制台

使用中间件的路由可以免除缓存。

// app/Http/routes.php

Route::get('/auth/logout', ['middleware' => 'doNotCacheResponse', 'uses' => 'AuthController@getLogout']);

或者,您可以将中间件添加到控制台中

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('doNotCacheResponse', ['only' => ['fooAction', 'barAction']]);
    }
}

创建自定义缓存配置文件

要确定哪些请求应该被缓存以及缓存多长时间,请使用缓存配置文件类。处理这些问题的默认类是Codeat3\ResponseCache\CacheProfiles\CacheAllSuccessfulGetRequests

您可以通过实现 Codeat3\ResponseCache\CacheProfiles\CacheProfile接口来创建自己的缓存配置文件类。让我们看看这个接口。

interface CacheProfile
{
    /*
     * Determine if the response cache middleware should be enabled.
     */
    public function enabled(Request $request): bool;

    /*
     * Determine if the given request should be cached.
     */
    public function shouldCacheRequest(Request $request): bool;

    /*
     * Determine if the given response should be cached.
     */
    public function shouldCacheResponse(Response $response): bool;

    /*
     * Return the time when the cache must be invalidated.
     */
    public function cacheRequestUntil(Request $request): DateTime;

    /**
     * Return a string to differentiate this request from others.
     *
     * For example: if you want a different cache per user you could return the id of
     * the logged in user.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return mixed
     */
    public function useCacheNameSuffix(Request $request);
}

缓存特定路由

除了全局注册cacheResponse中间件外,您还可以将其注册为路由中间件。

protected $routeMiddleware = [
   ...
   'cacheResponse' => \Codeat3\ResponseCache\Middlewares\CacheResponse::class,
];

使用路由中间件时,您可以指定这些路由应该缓存多长时间

// cache this route for 5 minutes
Route::get('/my-special-snowflake', 'SnowflakeController@index')->middleware('cacheResponse:300');

// cache all these routes for 10 minutes
Route::group(function() {
   Route::get('/another-special-snowflake', 'AnotherSnowflakeController@index');

   Route::get('/yet-another-special-snowflake', 'YetAnotherSnowflakeController@index');
})->middleware('cacheResponse:600');

使用标签

如果配置的缓存驱动程序支持标签,在应用中间件时可以指定一个标签列表。

// add a "foo" tag to this route with a 300 second lifetime
Route::get('/test1', 'SnowflakeController@index')->middleware('cacheResponse:300,foo');

// add a "bar" tag to this route
Route::get('/test2', 'SnowflakeController@index')->middleware('cacheResponse:bar');

// add both "foo" and "bar" tags to these routes
Route::group(function() {
   Route::get('/test3', 'AnotherSnowflakeController@index');

   Route::get('/test4', 'YetAnotherSnowflakeController@index');
})->middleware('cacheResponse:foo,bar');

清除带标签的内容

可以清除被分配了标签或标签列表的响应。例如,此语句将删除上面指定的所有路由

ResponseCache::clear(['foo', 'bar']);

相反,此语句将删除除了 '/test1' 路由之外的所有路由

ResponseCache::clear(['bar']);

注意,这使用的是 Laravel 内置的缓存标签功能,这意味着路由也可以按照常规方式清除

Cache::tags('special')->flush();

事件

您可以使用几个事件来监视和调试应用程序中的响应缓存。

ResponseCacheHit

Codeat3\ResponseCache\Events\ResponseCacheHit

当请求通过 ResponseCache 中间件并且找到并返回缓存的响应时,会触发此事件。

CacheMissed

Codeat3\ResponseCache\Events\CacheMissed

当请求通过 ResponseCache 中间件但没有找到或返回缓存的响应时,会触发此事件。

ClearingResponseCache 和 ClearedResponseCache

Codeat3\ResponseCache\Events\ClearingResponseCache

Codeat3\ResponseCache\Events\ClearedResponseCache

当开始和完成 responsecache:clear 时,分别触发这些事件。

创建一个 Replacer

要替换缓存内容为动态内容,可以创建一个替换器。默认情况下,我们在配置文件中添加了 CsrfTokenReplacer

您可以通过实现 Codeat3\ResponseCache\Replacers\Replacer 接口来创建自己的替换器。让我们看看这个接口

interface Replacer
{
    /*
     * Transform the initial response before it gets cached.
     *
     * For example: replace a generated csrf_token by '<csrf-token-here>' that you can
     * replace with its dynamic counterpart when the cached response is returned.
     */
    public function transformInitialResponse(Response $response): void;

    /*
     * Replace any data you want in the cached response before it gets
     * sent to the browser.
     *
     * For example: replace '<csrf-token-here>' by a call to csrf_token()
     */
    public function replaceCachedResponse(Response $response): void;
}

之后,您可以在 responsecache.php 配置文件中定义您的替换器

/*
 * Here you may define replacers that dynamically replace content from the response.
 * Each replacer must implement the Replacer interface.
 */
'replacers' => [
    \Codeat3\ResponseCache\Replacers\CsrfTokenReplacer::class,
],

自定义序列化器

序列化器负责将响应序列化以便存储在缓存中。它还负责从缓存中重建响应。

默认序列化器 Codeat3\ResponseCache\Serializer\DefaultSerializer 在大多数情况下都可以正常工作。

如果您有一些特殊的序列化需求,可以在配置文件的 serializer 键中指定自定义序列化器。任何实现了 Codeat3\ResponseCache\Serializers\Serializer 的类都可以使用。这是该接口的外观

namespace Codeat3\ResponseCache\Serializers;

use Symfony\Component\HttpFoundation\Response;

interface Serializer
{
    public function serialize(Response $response): string;

    public function unserialize(string $serializedResponse): Response;
}

变更日志

请参阅 CHANGELOG 了解最近更改的详细信息。

测试

您可以使用以下命令运行测试

composer test

替代方案

贡献

请参阅 CONTRIBUTING 了解详细信息。

安全性

如果您发现任何安全问题,请通过电子邮件发送到 freek@spatie.becode.at.three@gmail.com,而不是使用问题跟踪器。

Postcardware

您可以自由使用此包,但如果它进入您的生产环境,我们非常感激您从您家乡向 Spatie 发送一张明信片,提及您正在使用哪个 Spatie 包。

Spatie 地址是:Spatie,Samberstraat 69D,2060 安特卫普,比利时。

Spatie 在其公司网站上发布所有收到的明信片 https://spatie.be/en/opensource/postcards

致谢

支持spatie

spatie是一家位于比利时安特卫普的网页设计公司。您可以在他们的网站上找到他们所有开源项目的概述:点击查看

您的业务是否依赖于他们的贡献?通过Patreon与他们取得联系并支持他们。所有的承诺都将用于分配人力进行维护和开发新功能。

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件