From: fabien Date: Wed, 11 Nov 2009 16:46:52 +0000 (+0000) Subject: optimized template loading as the source code is now never fetched if the cache exist... X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=84113a960c71ddbb90d1dff849ebb0016944de43;p=konrad%2Ftwig.git optimized template loading as the source code is now never fetched if the cache exists and autoreload is false (which should be the case for websites in production) git-svn-id: http://svn.twig-project.org/trunk@129 93ef8e89-cb99-4229-a87c-7fa0fa45744b --- diff --git a/lib/Twig/Loader.php b/lib/Twig/Loader.php index c87bc0a..7607c34 100644 --- a/lib/Twig/Loader.php +++ b/lib/Twig/Loader.php @@ -66,31 +66,34 @@ abstract class Twig_Loader implements Twig_LoaderInterface return $cls; } - list($template, $mtime) = $this->getSource($name); - if (false === $this->cache) { - $this->evalString($template, $name); + list($source, ) = $this->getSource($name); + $this->evalString($source, $name); return $cls; } $cache = $this->getCacheFilename($name); - if (!file_exists($cache) || false === $mtime || ($this->autoReload && (filemtime($cache) < $mtime))) + if (!file_exists($cache)) { - // compile first to avoid empty files when an Exception occurs - $content = $this->compile($template, $name); - - $fp = @fopen($cache, 'wb'); - if (!$fp) + list($source, $mtime) = $this->getSource($name); + if (false === $mtime) { - eval('?>'.$content); + $this->evalString($source, $name); return $cls; } - fclose($fp); - file_put_contents($cache, $content); + $this->save($this->compile($source, $name), $cache); + } + elseif ($this->autoReload) + { + list($source, $mtime) = $this->getSource($name); + if (filemtime($cache) < $mtime) + { + $this->save($this->compile($source, $name), $cache); + } } require_once $cache; @@ -99,6 +102,27 @@ abstract class Twig_Loader implements Twig_LoaderInterface } /** + * Saves a PHP string in the cache. + * + * If the cache file cannot be written, then the PHP string is evaluated. + * + * @param string $content The PHP string + * @param string $cache The absolute path of the cache + */ + protected function save($content, $cache) + { + if ($fp = @fopen($cache, 'w')) + { + fclose($fp); + file_put_contents($cache, $content); + } + else + { + eval('?>'.$content); + } + } + + /** * Sets the Environment related to this loader. * * @param Twig_Environment $env A Twig_Environment instance