Reputation: 442
What is the best practice for setting container parameters that need to be properly setup, e.g. I have a parameter called 'feed_filesystem_cache_path' (string of '%kernel.cache_dir%' + /directory location) which I am injecting into some service classes.
I see myself checking on existance in those classes and would like to know if there's a better way to do that.
I've tried to alter my bundle's container extension, but seems like the parameters aren't resolved by then; I'm still getting '%kernel.cache_dir%/feeds' instead of a fully qualified/compiled path.
Trying in Bundle class, in the build method (just after parent::build($container) isn't helping me much either, at that point the containe only has "kernel" services and parameters.
Upvotes: 0
Views: 192
Reputation: 7525
Converting my comment into an answer to have a decent reply to this question
A reasonnable way to do this, is to create a Cache Warmer
To do so, you need to create a new service, and tag it with kernel.cache_warmer
services.yml
services:
acme_foo.my_warmer:
class: Acme\FooBundle\CacheWarmer
arguments:
- @filesystem
tags:
- name: kernel.cache_warmer
- priority: 0
A cache warmer must implement CacheWarmerInterface.
namespace Acme\FooBundle;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface
class CacheWarmer implements CacheWarmerInterface
{
protected $filesystem;
public function __construct(Filesystem $filesystem)
{
$this->filesystem = $filesystem;
}
/**
* {@inheritDoc}
*/
public function warmUp($cacheDir)
{
$real = sprintf("%s/feeds", $cacheDir);
$this->filesystem->mkdir($real);
}
/**
* {@inheritDoc}
*/
public function isOptional()
{
return true;
}
}
With this component, the directory /feeds
will be created when you execute cache:clear
(without --no-warmup) or cache:warmup
command.
It worth mentionning that you may check in your application that the directory exists, to prevent any fatal error in case of your cache haven't been warmed up
$filename = "/cache/dir/feeds/file";
if (!is_dir(dirname($filename))) {
mkdir(dirname($filename));
}
Upvotes: 2