這個 Laravel 套件可以緩存整個回應。預設情況下,它將快取所有傳回基於文字的內容(例如 html 和 json)的成功取得請求一週。這可能會大大加快響應速度。
因此,第一次請求進入包時將保存回應,然後再將其發送給用戶。當相同的請求再次出現時,我們不會遍歷整個應用程序,而只是使用已儲存的回應進行回應。
你是視覺學習者嗎?然後觀看此視頻,其中介紹瞭如何使用 laravel-responsecache 及其幕後工作原理。
我們投入了大量資源來創建一流的開源套件。您可以透過購買我們的一款付費產品來支持我們。
我們非常感謝您從家鄉寄給我們一張明信片,並註明您正在使用我們的哪種套餐。您可以在我們的聯絡頁面上找到我們的地址。我們在虛擬明信片牆上發布所有收到的明信片。
如果您使用 PHP 7,請安裝此軟體套件的 v6.x。
您可以透過 Composer 安裝該軟體包:
composer require spatie/laravel-responsecache
該包將自動註冊。
您可以使用以下方式發布設定檔:
php artisan vendor:publish --tag= " responsecache-config "
這是已發布的設定檔的內容:
// 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 ' => Spatie ResponseCache CacheProfiles CacheAllSuccessfulGetRequests::class,
/ *
* Optionally , you can specify a header that will force a cache bypass .
* This can be useful to monitor the performance of your application .
* /
' cache_bypass_header ' => [
' name ' => env ( ' CACHE_BYPASS_HEADER_NAME ' , null ),
' value ' => env ( ' CACHE_BYPASS_HEADER_VALUE ' , null ),
],
/ *
* 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 * 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 ' ),
/ *
* This setting determines if a http header named with the cache age
* should be added to a cached response . This can be handy when
* debugging .
* ONLY works when "add_cache_time_header" is also active !
* /
' add_cache_age_header ' => env ( ' RESPONSE_CACHE_AGE_HEADER ' , false ),
/ *
* This setting determines the name of the http header that contains
* the age of cache
* /
' cache_age_header_name ' => env ( ' RESPONSE_CACHE_AGE_HEADER_NAME ' , ' laravel-responsecache-age ' ),
/ *
* 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 ' => [
Spatie 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 ' => Spatie ResponseCache Hasher DefaultHasher::class,
/ *
* This class is responsible for serializing responses .
* /
' serializer ' => Spatie ResponseCache Serializers DefaultSerializer::class,
];
最後,您應該安裝提供的中間件SpatieResponseCacheMiddlewaresCacheResponse::class
和SpatieResponseCacheMiddlewaresDoNotCacheResponse
。
對於 laravel 11.x 及更高版本:
將中間件定義新增至引導應用程式。
// bootstrap / app . php
-> withMiddleware ( function ( Middleware $ middleware ) {
. . .
$ middleware -> web (append: [
...
Spatie ResponseCache Middlewares CacheResponse::class,
]);
. . .
$ middleware -> alias ([
...
' doNotCacheResponse ' => Spatie ResponseCache Middlewares DoNotCacheResponse::class,
]);
})
對於 laravel 10.x 及更早版本:
將中間件定義加入到 http 核心。
// app / Http / Kernel . php
. . .
protected $ middlewareGroups = [
' web ' => [
...
Spatie ResponseCache Middlewares CacheResponse::class,
],
...
protected $ middlewareAliases = [
...
' doNotCacheResponse ' => Spatie ResponseCache Middlewares DoNotCacheResponse::class,
];
預設情況下,該包會將所有成功的GET
請求快取一週。每個登入用戶都有自己單獨的快取。如果您需要這種行為,那麼您就完成了:安裝ResponseCacheServiceProvider
就足夠了。
可以使用以下命令清除整個快取:
ResponseCache:: clear ();
這將清除設定檔中指定的快取儲存中的所有內容。
可以透過發出以下 artisan 指令來完成相同的任務:
php artisan responsecache:clear
每當儲存或刪除模型時,您都可以利用模型事件來清除快取。這是一個例子。
namespace App Traits ;
use Spatie 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:
// Forget one
ResponseCache:: forget ( ' /some-uri ' );
// Forget several
ResponseCache:: forget ([ ' /some-uri ' , ' /other-uri ' ]);
// Equivalent to the example above
ResponseCache:: forget ( ' /some-uri ' , ' /other-uri ' );
ResponseCache::forget
方法僅在您的快取設定檔中未使用cacheNameSuffix
時才有效,請使用ResponseCache::selectCachedItems
來處理cacheNameSuffix
。
您可以使用ResponseCache::selectCachedItems()
指定應忘記哪些快取項目。
// forgetting all PUT responses of / some - uri
ResponseCache:: selectCachedItems ()-> withPutMethod ()-> forUrls ( ' /some-uri ' )-> forget ();
// forgetting all PUT responses of multiple endpoints
ResponseCache:: selectCachedItems ()-> withPutMethod ()-> forUrls ([ ' /some-uri ' , ' /other-uri ' ])-> forget ();
// this is equivalent to the example above
ResponseCache:: selectCachedItems ()-> withPutMethod ()-> forUrls ( ' /some-uri ' , ' /other-uri ' )-> forget ();
// forget / some - uri cached with "100" suffix ( by default suffix is user - > id or "" )
ResponseCache:: selectCachedItems ()-> usingSuffix ( ' 100 ' )-> forUrls ( ' /some-uri ' )-> forget ();
// all options combined
ResponseCache:: selectCachedItems ()
-> withPutMethod ()
-> withHeaders ([ ' foo ' => ' bar ' ])
-> withCookies ([ ' cookie1 ' => ' value ' ])
-> withParameters ([ ' param1 ' => ' value ' ])
-> withRemoteAddress ( ' 127.0.0.1 ' )
-> usingSuffix ( ' 100 ' )
-> usingTags ( ' tag1 ' , ' tag2 ' )
-> forUrls ( ' /some-uri ' , ' /other-uri ' )
-> forget ();
cacheNameSuffix
取決於您的快取配置文件,預設是使用者 ID,如果未經過身份驗證,則為空字串。
使用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 ' ]]);
}
}
可以有目的地、安全地繞過快取並確保您始終收到新的回應。如果您想要分析某個端點或需要偵錯回應,這可能很有用。在任何情況下,您所需要做的就是填入CACHE_BYPASS_HEADER_NAME
和CACHE_BYPASS_HEADER_VALUE
環境變量,然後在執行請求時使用該自訂標頭。
為了確定應該快取哪些請求以及快取多長時間,需要使用快取設定檔類別。處理這些問題的預設類別是SpatieResponseCacheCacheProfilesCacheAllSuccessfulGetRequests
。
您可以透過實作SpatieResponseCacheCacheProfilesCacheProfile
介面來建立自己的快取設定檔類別。我們看一下介面:
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 $ middlewareAliases = [
...
' cacheResponse ' => Spatie 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 ' );
您可以清除已指派了標籤或標籤清單的回應。例如,此語句將刪除上面的'/test3'
和'/test4'
路由:
ResponseCache:: clear ([ ' foo ' , ' bar ' ]);
相反,此語句將僅刪除'/test2'
路由:
ResponseCache:: clear ([ ' bar ' ]);
請注意,這使用了 Laravel 內建的快取標籤功能,這意味著也可以透過通常的方式清除路由:
Cache:: tags ( ' special ' )-> flush ();
您可以使用多個事件來監視和調試應用程式中的回應快取。
SpatieResponseCacheEventsResponseCacheHit
當請求通過ResponseCache
中間件並且找到並傳回快取的回應時,會觸發此事件。
SpatieResponseCacheEventsCacheMissed
當請求通過ResponseCache
中間件但未找到或傳回快取的回應時,會觸發此事件。
SpatieResponseCacheEventsClearingResponseCache
SpatieResponseCacheEventsClearedResponseCache
這些事件分別在responsecache:clear
啟動和完成時觸發。
若要用動態內容取代快取內容,您可以建立替換器。預設情況下,我們在設定檔中加入CsrfTokenReplacer
。
您可以透過實作SpatieResponseCacheReplacersReplacer
介面來建立自己的替換器。我們看一下介面:
interface Replacer
{
/ *
* Prepare 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 prepareResponseToCache ( 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 replaceInCachedResponse ( 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' => [
SpatieResponseCacheReplacersCsrfTokenReplacer::class,
],
序列化器負責序列化回應,以便將其儲存在快取中。它還負責從緩存重建響應。
預設序列化器SpatieResponseCacheSerializerDefaultSerializer
在大多數情況下都可以工作。
如果您有一些特殊的序列化需求,您可以在設定檔的serializer
鍵中指定自訂序列化程式。可以使用任何實作SpatieResponseCacheSerializersSerializer
的類別。該介面如下所示:
namespace Spatie ResponseCache Serializers ;
use Symfony Component HttpFoundation Response ;
interface Serializer
{
public function serialize ( Response $ response ): string ;
public function unserialize ( string $ serializedResponse ): Response ;
}
您可以使用以下命令執行測試:
composer test
請參閱變更日誌以了解最近變更的更多資訊。
詳細資訊請參閱貢獻。
如果您發現有關安全的錯誤,請發送郵件至 [email protected],而不是使用問題追蹤器。
特別感謝 Caneco 的標誌
麻省理工學院許可證 (MIT)。請參閱許可證文件以獲取更多資訊。