Skip to content

Commit 6e439d5

Browse files
authored
Introduce using() method to conveniently define lifetime and tags (spatie#491)
* Introduce using() method to conveniently define lifetime and tags * Document and test CacheResponse::using middleware helper
1 parent 6d98980 commit 6e439d5

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,8 @@ Route::group(function() {
404404
If the [cache driver you configured supports tags](https://laravel.com/docs/5.8/cache#cache-tags), you can specify a list of tags when applying the middleware.
405405

406406
```php
407+
use Spatie\ResponseCache\Middlewares\CacheResponse;
408+
407409
// add a "foo" tag to this route with a 300 second lifetime
408410
Route::get('/test1', 'SnowflakeController@index')->middleware('cacheResponse:300,foo');
409411

@@ -416,6 +418,9 @@ Route::group(function() {
416418

417419
Route::get('/test4', 'YetAnotherSnowflakeController@index');
418420
})->middleware('cacheResponse:foo,bar');
421+
422+
// or use the using method for convenience
423+
Route::get('/test5', 'SnowflakeController@index')->middleware(CacheResponse::using(300, 'foo', 'bar'));
419424
```
420425

421426
#### Clearing tagged content

src/Middlewares/CacheResponse.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ public function __construct(ResponseCache $responseCache)
2323
$this->responseCache = $responseCache;
2424
}
2525

26+
public static function using($lifetime, ...$tags): string
27+
{
28+
return static::class.':'.implode(',', [$lifetime, ...$tags]);
29+
}
30+
2631
public function handle(Request $request, Closure $next, ...$args): Response
2732
{
2833
$lifetimeInSeconds = $this->getLifetime($args);

tests/TaggingTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use function PHPUnit\Framework\assertThat;
44
use function PHPUnit\Framework\isTrue;
55

6+
use Spatie\ResponseCache\Middlewares\CacheResponse;
67
use Spatie\ResponseCache\Test\Concerns\CanChangeCacheStore;
78

89
uses(CanChangeCacheStore::class);
@@ -77,3 +78,14 @@
7778
assertRegularResponse($secondResponse);
7879
assertDifferentResponse($firstResponse, $secondResponse);
7980
});
81+
82+
it('can generate middleware string for different tag combinations using the using method', function () {
83+
$singleTag = CacheResponse::using('foo');
84+
expect($singleTag)->toBe(CacheResponse::class.':foo');
85+
86+
$multipleTags = CacheResponse::using('foo', 'bar');
87+
expect($multipleTags)->toBe(CacheResponse::class.':foo,bar');
88+
89+
$lifetime = CacheResponse::using(300);
90+
expect($lifetime)->toBe(CacheResponse::class.':300');
91+
});

0 commit comments

Comments
 (0)