symfonyclear-cachefoshttpcachebundle

How can I clear the cache of the frontend in my Smfony controller?


I would like to clear the website cache of my frontend whenever I make an update of a page in the backend.

This is my approach:

use FOS\HttpCacheBundle\CacheManager;

class ProjectController extends AbstractRestController
{
private CacheManager $cacheManager;

   public function __construct(
        CacheManager $cacheManager
    ) {
        $this->cacheManager = $cacheManager;  
        parent::__construct($viewHandler, $tokenStorage);
    }

    protected function mapDataToEntity(array $data, Project $entity): void{
     $entity->setName($data['name']);
     $this->cacheManager->invalidatePath($path, $headers);
        
    }
}

I get the error message:

Warning: Undefined variable $path

because I am not really sure why I need to create a variable "path". I would like to clear the cache of the whole website. Is this possible this way?


Solution

  • You can use this method in your controller, but I am not sure this will be a good idea to clear the cache in your controller every time you are in your /url.

    <php
    
    private function celearCache(KernelInterface $kernel): void
    {
        
        $application = new Application($kernel);
        $application->setAutoExit(false);
    
        $env = $kernel->getEnvironment();
    
        $input = new ArrayInput([
            'command' => 'cache:clear',
            '--env' => $env
        ]);
    
        // You can use NullOutput() if you don't need the output
        $output = new BufferedOutput();
        $application->run($input, $output);
    }
    

    For more details about using commands in controllers see the official documentation.