Calamity Jane
Calamity Jane

Reputation: 2686

Symfony4: How can I access the path to the cache directory from a service

I want to access the path to the cache directory from a service to save some temporary files there. In Symfony2 that was not problem, but I am stuck how to achieve that in Symfony4.

If I access the ParameterBag I find the value of the log directory, but not the one of the cache directory.

Although the Kernel.php has the method

public function getCacheDir()
{
    return $this->getProjectDir().'/var/cache/'.$this->environment;
}

I am not sure how to access that either from a service.

What is the correct way to do this in symfony 4?

Upvotes: 2

Views: 2036

Answers (1)

Calamity Jane
Calamity Jane

Reputation: 2686

My bad.... so you can access the information.

If you are in a service you have to pass in the constructor of your service the ParameterBag like this:

/** @var ParameterBagInterface */
private $params;

private $cachePath;

public function __construct(LoggerInterface $logger, ParameterBagInterface $params)
{
    $this->params = $params;
    $this->cachePath = $this->prepareCacheDir();
    $this->logger = $logger;
}

So later in your method you can do the following:

private function prepareCacheDir()
{
    $kernelCache =  $this->params->get('kernel.cache_dir');
    $cachepath = $kernelCache . DIRECTORY_SEPARATOR . 'sqlDumps'
        . DIRECTORY_SEPARATOR . date_format(date_create(), 'Y_m_d');

    return $cachepath;
}

Important: write a value, before trying to read it. My error was, that I user $this->param before I had set the value in the constructor.

Upvotes: 3

Related Questions