danilovl/cache-response-bundle

Symfony bundle provides cache controller response

v0.5.7 2024-10-28 10:39 UTC

This package is auto-updated.

Last update: 2024-10-28 10:40:54 UTC


README

phpunit downloads latest Stable Version license

CacheResponseBundle

About

Symfony bundle provides simple cache response.

Before:

Alt text

After:

Alt text

Requirements

  • PHP 8.3 or higher
  • Symfony 7.0 or higher

1. Installation

Install danilovl/cache-response-bundle package by Composer:

composer require danilovl/cache-response-bundle

Add the CacheResponseBundle to your application's bundles if does not add automatically:

<?php
// config/bundles.php

return [
    // ...
    Danilovl\CacheResponseBundle\CacheResponseBundle::class => ['all' => true]
];

2. Usage

You can define custom cache service witch implement CacheItemPoolInterface.

# config/packages/danilovl_cache_response.yaml

danilovl_cache_response:
  service: You service name

2.1 Controller

Add attribute CacheResponseAttribute to controller method.

#[CacheResponseAttribute(
    cacheKey: 'index', 
    expiresAfter: 60, 
    cacheKeyWithQuery: true, 
    cacheKeyWithRequest: true
)]
public function index(Request $request): Response
{
    return new Response('content');
}

Or better solution if you have duplicate controller name and method name.

#[CacheResponseAttribute(
    cacheKey: __METHOD__, 
    expiresAfter: 60, 
    cacheKeyWithQuery: true, 
    cacheKeyWithRequest: true
)]
public function index(Request $request): Response
{
    return new Response('content');
}

Use custom factory service for create cache key. Must implements interface CacheKeyFactoryInterface.

#[CacheResponseAttribute(cacheKeyFactory: CachKeyFactoryClass::class)]
public function index(Request $request): Response
{
    return new Response('content');
}

2.2 Command

Show all used CacheResponseAttribute cache key names.

php bin/console danilovl:cache-response:list 

Alt text

Clear all CacheResponseAttribute cache.

php bin/console danilovl:cache-response:clear --all=true

Clear only specific CacheResponseAttribute cache key name.

php bin/console danilovl:cache-response:clear --cacheKey=index

Clear all similar CacheResponseAttribute cache key name.

0 => "danilovl.cache_response.8414b2ff0a6fafcddc0f42d6d5a5b908d34925c3"
1 => "danilovl.cache_response.8414b2ff08997b2bd029eaab1a04598a500a0034"
php bin/console danilovl:cache-response:clear --similarCacheKey=8414b2ff0
0 => "danilovl.cache_response.8414b2ff0a6fafcddc0f42d6d5a5b90similar"
1 => "danilovl.cache_response.8414b2ff08997b2bd029eaab1a04598similar"
php bin/console danilovl:cache-response:clear --cacheKey=similar

2.3 EventSubscriber

Clear all cache.

$this->eventDispatcher->dispatch(new ClearCacheResponseAllEvent);

Clear only specific cache key.

$this->eventDispatcher->dispatch(new ClearCacheResponseKeyEvent('cache_key'));

License

The CacheResponseBundle is open-sourced software licensed under the MIT license.