symfonycachingmethodssulu

How can I use the a cache manager in Symfony?


I my contoller I try to clear the cache when updating a page

protected function mapDataToEntity(array $data, Project $entity): void{
    
    $entity->setName($data['name']);

    $cacheManager = $this->get('sulu_http_cache.cache_manager');
    $cacheManager->invalidatePath($path, $headers);
}

I get the error message:

Attempted to call an undefined method named "get" of class "App\Controller\Admin\ProjectController". Did you mean to call e.g. "cgetAction", "getAction", "getLocale" or "getSecurityContext"?


Solution

  • You should autowire your cache manager instead of trying to access it from the container.

    private CacheManager $cacheManager;
    
    public function __construct(CacheManager $cacheManager)
    {
        $this->cacheManager = $cacheManager;
    }
    

    And use it in your method:

    $this->cacheManager->invalidatePath($path, $headers);