Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a PHP Array parsed from a YAML file in Symfony's cache

I have a few YAML files to be parsed from a service.

But at every page hit, those YAML files are parsed and converted to a PHP Array. I understand Symfony keeps the default YAML files cached, so it doesn't parse every yaml file at every page hit.

I was wondering what is the best practice here. Is there a way to have my YAML files parsed only once and stored with Symfony2's cache? If so, could I please be pointed in the right direction?

like image 886
Pedro Cordeiro Avatar asked Oct 22 '22 13:10

Pedro Cordeiro


1 Answers

It all depends on how you want to do the caching.

  • HTTP caching really only makes sense when in the web context and when the particular output of the action where you're parsing and adding these files to an array is relatively static. If both of those conditions are met, then that is the best way to go.

  • You can easily use APC to do your caching. It makes caching the contents of a variable quite simple. Doctrine provides a cache abstraction around APC, or you can use native PHP functions.

in config.yml

 services:
        cache:
            class: Doctrine\Common\Cache\ApcCache

then in your controller or service:

if ($yamlArray = $this->get('cache')->fetch('foo')) {
    $yamlArray = unserialize($yamlArray);
} else {
    // do the work
    $this->get('cache')->save('foo', serialize($yamlArray));
}
  • Make your own caching service and hook it into the Symfony cache commands

Details on creating a cache warmer

Details on cache_clearer(added but not well documented).

like image 154
james_t Avatar answered Nov 04 '22 00:11

james_t