Cache Clear Service
How to call Symfony's cache:clear service ?
Post by Pedro Resende on the 18 of August of 2017 at 16:31
Tags: cachesymfonyclearservice
This week, while working on a project for a customer, I've decided to implement a clear cache service command.
I know I've done something similar in the past, but this time the idea was to use a service.
I've started by creating a new folder, under your bundle called Services.
In side that folder, I've add a file called Cache.php with the following:
<?php
namespace Acme\Services;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Bundle\FrameworkBundle\Console\Application;
/**
* Cache Class responsible for dealing with clear cache command
*
* @author Pedro Resende <pedroresende@mail.resende.biz>
*/
class Cache
{
/**
* Symfony's Kernel Service
*
* @var [type]
*/
private $kernel;
public function __construct($kernel)
{
$this->kernel = $kernel;
}
/**
* This Method is responsible for triggering the cache clear command
*
* @return void
*/
public function clearCache()
{
$input = new Argvinput(array('console','cache:clear'));
$application = new Application($this->kernel);
$application->run($input);
}
}
Now, open you services.yml file, under Acme/Resources/services.yml, and add the following:
clear.cache:
lazy: true
class: Acme\Services\Cache
arguments: [@kernel]
Now, to call this service inside a Controller, you'll simply will need to do:
$cache = $this->container->get('clear.cache');
$cache->clearCache();
Finally, you have to run the following command, to support the lazy service.
$ composer require ocramius/proxy-manager
And it will clear your cache