In order to have caching on methods you need to install it using composer:
- Add requirement:
$ composer require emag/cache-bundle- Add to your app/AppKernel.php
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
//...
new Emag\CacheBundle\EmagCacheBundle(),
//...
];
//...
}
//....
}- Configure the bundle required info
You have to configure the name of the service that is PSR6 compliant, that means it will have to implement Psr\Cache\CacheItemPoolInterface:
# app/config/services.yml
services:
cache.array:
class: Symfony\Component\Cache\Adapter\ArrayAdapter
cache.redis:
class: Symfony\Component\Cache\Adapter\RedisAdapter
arguments: ['@predis'] #app/config/config.yml
# eMAG CachingBundle
emag_cache:
provider: cache.redis
ignore_namespaces:
- 'Symfony\\'
- 'Doctrine\\'
- 'Twig_'
- 'Monolog\\'
- 'Swift_'
- 'Sensio\\Bundle\\'EmagCacheBundle comes with 2 different ways you can add annotation cache to your service:
- @Cache annotation
Add @Cache annotation to the methods you want to be cached:
use Emag\CacheBundle\Annotation\Cache;
/**
* @Cache(cache="<put your prefix>", [key="<name of argument to include in cache key separated by comma>", [ttl=600, [reset=true ]]])
*/Here is an example from a service:
namespace AppCacheBundle\Service;
use Emag\CacheBundle\Annotation\Cache;
class AppService
{
/**
* @Cache(cache="app_high_cpu", ttl=60)
*
* @return int
*/
public function getHighCPUOperation()
{
// 'Simulate a time consuming operation';
sleep(10);
return 20;
}
}- @CacheExpression annotation witch uses Symfony ExpressionLanguage component:
use Emag\CacheBundle\Annotation\CacheExpression;
/**
* @CacheExpression(cache="<put your expression language code>", [key="<name of argument to include in cache key separated by comma>", [ttl=600, [reset=true ]]])
*/Here is an example from a service:
namespace AppCacheBundle\Service;
use Emag\CacheBundle\Annotation as eMAG;
class AppService
{
/** @var string */
private $prefix;
public function __construct(string $prefix)
{
$this->prefix = $prefix;
}
/**
* @eMAG\CacheExpression(cache="this.buildCachePrefix()")
*
* @return int
*/
public function getIntenseResult() : int
{
// 'Simulate a time consuming operation';
sleep(20);
return rand();
}
/**
* @return string
*/
public function buildCachePrefix() : string
{
return sprintf('_expr[%s]', $this->prefix);
}
}Submit a PR and join the fun.
Enjoy!
