CacheLoader.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace Symfony\Components\Templating\Loader;
  3. use Symfony\Components\Templating\Storage\Storage;
  4. use Symfony\Components\Templating\Storage\FileStorage;
  5. /*
  6. * This file is part of the symfony package.
  7. *
  8. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  9. *
  10. * For the full copyright and license information, please view the LICENSE
  11. * file that was distributed with this source code.
  12. */
  13. /**
  14. * CacheLoader is a loader that caches other loaders responses
  15. * on the filesystem.
  16. *
  17. * This cache only caches on disk to allow PHP accelerators to cache the opcodes.
  18. * All other mecanism would imply the use of `eval()`.
  19. *
  20. * @package symfony
  21. * @subpackage templating
  22. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  23. */
  24. class CacheLoader extends Loader
  25. {
  26. protected $loader;
  27. protected $dir;
  28. /**
  29. * Constructor.
  30. *
  31. * @param Loader $loader A Loader instance
  32. * @param string $dir The directory where to store the cache files
  33. */
  34. public function __construct(Loader $loader, $dir)
  35. {
  36. $this->loader = $loader;
  37. $this->dir = $dir;
  38. if (!file_exists($dir))
  39. {
  40. mkdir($dir, 0777, true);
  41. }
  42. parent::__construct();
  43. }
  44. /**
  45. * Loads a template.
  46. *
  47. * @param string $template The logical template name
  48. * @param array $options An array of options
  49. *
  50. * @return Storage|Boolean false if the template cannot be loaded, a Storage instance otherwise
  51. */
  52. public function load($template, array $options = array())
  53. {
  54. $options = $this->mergeDefaultOptions($options);
  55. $path = $this->dir.DIRECTORY_SEPARATOR.md5($template.serialize($options)).'.tpl';
  56. if ($this->loader instanceof CompilableLoaderInterface)
  57. {
  58. $options['renderer'] = 'php';
  59. }
  60. if (file_exists($path))
  61. {
  62. if (null !== $this->debugger)
  63. {
  64. $this->debugger->log(sprintf('Fetching template "%s" from cache', $template));
  65. }
  66. return new FileStorage($path, $options['renderer']);
  67. }
  68. if (false === $storage = $this->loader->load($template, $options))
  69. {
  70. return false;
  71. }
  72. $content = $storage->getContent();
  73. if ($this->loader instanceof CompilableLoaderInterface)
  74. {
  75. $content = $this->loader->compile($content);
  76. }
  77. file_put_contents($path, $content);
  78. if (null !== $this->debugger)
  79. {
  80. $this->debugger->log(sprintf('Storing template "%s" in cache', $template));
  81. }
  82. return new FileStorage($path, $options['renderer']);
  83. }
  84. }