PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 16, 2022

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

 October 16, 2022     clear-cache, foshttpcachebundle, symfony     No comments   

Issue

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.



Answered By - Houssem ZITOUN
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,205,581

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing