Development

/branches/1.1/lib/view/sfViewCacheManager.class.php

You must first sign up to be able to contribute.

root/branches/1.1/lib/view/sfViewCacheManager.class.php

Revision 19850, 25.4 kB (checked in by FabianLange, 5 years ago)

[1.2, 1.2, 1.3] fixed PHPdoc typo

  • Property svn:mime-type set to text/x-php
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Rev Date
Line 
1 <?php
2
3 /*
4  * This file is part of the symfony package.
5  * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
6  *
7  * For the full copyright and license information, please view the LICENSE
8  * file that was distributed with this source code.
9  */
10
11 /**
12  * Cache class to cache the HTML results for actions and templates.
13  *
14  * This class uses a sfCache instance implementation to store cache.
15  *
16  * To disable all caching, you can set the [sf_cache] constant to false.
17  *
18  * @package    symfony
19  * @subpackage view
20  * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
21  * @version    SVN: $Id$
22  */
23 class sfViewCacheManager
24 {
25   protected
26     $cache       = null,
27     $cacheConfig = array(),
28     $context     = null,
29     $dispatcher  = null,
30     $controller  = null,
31     $routing     = null,
32     $loaded      = array();
33
34   /**
35    * Class constructor.
36    *
37    * @see initialize()
38    */
39   public function __construct($context, sfCache $cache)
40   {
41     $this->initialize($context, $cache);
42   }
43
44   /**
45    * Initializes the cache manager.
46    *
47    * @param sfContext $context  Current application context
48    * @param sfCache   $cache    An sfCache instance
49    */
50   public function initialize($context, sfCache $cache)
51   {
52     $this->context    = $context;
53     $this->dispatcher = $context->getEventDispatcher();
54     $this->controller = $context->getController();
55
56     // empty configuration
57     $this->cacheConfig = array();
58
59     // cache instance
60     $this->cache = $cache;
61
62     // routing instance
63     $this->routing = $context->getRouting();
64   }
65
66   /**
67    * Retrieves the current cache context.
68    *
69    * @return sfContext The sfContext instance
70    */
71   public function getContext()
72   {
73     return $this->context;
74   }
75
76   /**
77    * Retrieves the current cache object.
78    *
79    * @return sfCache The current cache object
80    */
81   public function getCache()
82   {
83     return $this->cache;
84   }
85
86   /**
87    * Generates a unique cache key for an internal URI.
88    * This cache key can be used by any of the cache engines as a unique identifier to a cached resource
89    *
90    * Basically, the cache key generated for the following internal URI:
91    *   module/action?key1=value1&key2=value2
92    * Looks like:
93    *   /localhost/all/module/action/key1/value1/key2/value2
94    *
95    * @param  string $internalUri       The internal unified resource identifier
96    *                                   Accepts rules formatted like 'module/action?key1=value1&key2=value2'
97    *                                   Does not accept rules starting with a route name, except for '@sf_cache_partial'
98    * @param  string $hostName          The host name
99    *                                   Optional - defaults to the current host name bu default
100    * @param  string $vary              The vary headers, separated by |, or "all" for all vary headers
101    *                                   Defaults to 'all'
102    * @param  string $contextualPrefix  The contextual prefix for contextual partials.
103    *                                   Defaults to 'currentModule/currentAction/currentPAram1/currentvalue1'
104    *                                   Used only by the sfViewCacheManager::remove() method
105    *
106    * @return string The cache key
107    *                If some of the parameters contained wildcards (* or **), the generated key will also have wildcards
108    */
109   public function generateCacheKey($internalUri, $hostName = '', $vary = '', $contextualPrefix = '')
110   {
111     if ($callable = sfConfig::get('sf_cache_namespace_callable'))
112     {
113       if (!is_callable($callable))
114       {
115         throw new sfException(sprintf('"%s" cannot be called as a function.', var_export($callable, true)));
116       }
117
118       return call_user_func($callable, $internalUri, $hostName, $vary, $contextualPrefix);
119     }
120
121     if (strpos($internalUri, '@') === 0 && strpos($internalUri, '@sf_cache_partial') === false)
122     {
123       throw new sfException('A cache key cannot be generated for an internal URI using the @rule syntax');
124     }
125
126     $cacheKey = '';
127
128     if ($this->isContextual($internalUri))
129     {
130       // Contextual partial
131       if (!$contextualPrefix)
132       {
133         list($route_name, $params) = $this->controller->convertUrlStringToParameters($this->routing->getCurrentInternalUri());
134         $cacheKey = $this->convertParametersToKey($params);
135       }
136       else
137       {
138         $cacheKey = $contextualPrefix;
139       }
140       list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
141       $cacheKey .= sprintf('/%s/%s/%s', $params['module'], $params['action'], isset($params['sf_cache_key']) ? $params['sf_cache_key'] : '');
142     }
143     else
144     {
145       // Regular action or non-contextual partial
146       list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
147       if ($route_name == 'sf_cache_partial')
148       {
149         $cacheKey = 'sf_cache_partial/';
150       }
151
152       $cacheKey .= $this->convertParametersToKey($params);
153     }
154
155     // prefix with vary headers
156     if (!$vary)
157     {
158       $varyHeaders = $this->getVary($internalUri);
159       if ($varyHeaders)
160       {
161         sort($varyHeaders);
162         $request = $this->context->getRequest();
163         $vary = '';
164
165         foreach ($varyHeaders as $header)
166         {
167           $vary .= $request->getHttpHeader($header).'|';
168         }
169
170         $vary = $vary;
171       }
172       else
173       {
174         $vary = 'all';
175       }
176     }
177
178     // prefix with hostname
179     if (!$hostName)
180     {
181       $request = $this->context->getRequest();
182       $hostName = $request->getHost();
183     }
184     $hostName = preg_replace('/[^a-z0-9\*]/i', '_', $hostName);
185     $hostName = strtolower(preg_replace('/_+/', '_', $hostName));
186
187     $cacheKey = sprintf('/%s/%s/%s', $hostName, $vary, $cacheKey);
188
189     // replace multiple /
190     $cacheKey = preg_replace('#/+#', '/', $cacheKey);
191
192     return $cacheKey;
193   }
194
195   /**
196    * Transforms an associative array of parameters from an URI into a unique key
197    *
198    * @param  array $params  Associative array of parameters from the URI (including, at least, module and action)
199    *
200    * @return string Unique key
201    */
202   protected function convertParametersToKey($params)
203   {
204     if(!isset($params['module']) || !isset($params['action']))
205     {
206       throw new sfException('A cache key must contain both a module and an action parameter');
207     }
208     $module = $params['module'];
209     unset($params['module']);
210     $action = $params['action'];
211     unset($params['action']);
212     ksort($params);
213     $cacheKey = sprintf('%s/%s', $module, $action);
214     foreach ($params as $key => $value)
215     {
216       $cacheKey .= sprintf('/%s/%s', $key, $value);
217     }
218
219     return $cacheKey;
220   }
221
222   /**
223    * Adds a cache to the manager.
224    *
225    * @param string $moduleName  Module name
226    * @param string $actionName  Action name
227    * @param array  $options     Options for the cache
228    */
229   public function addCache($moduleName, $actionName, $options = array())
230   {
231     // normalize vary headers
232     if (isset($options['vary']))
233     {
234       foreach ($options['vary'] as $key => $name)
235       {
236         $options['vary'][$key] = strtr(strtolower($name), '_', '-');
237       }
238     }
239
240     $options['lifeTime'] = isset($options['lifeTime']) ? $options['lifeTime'] : 0;
241     if (!isset($this->cacheConfig[$moduleName]))
242     {
243       $this->cacheConfig[$moduleName] = array();
244     }
245     $this->cacheConfig[$moduleName][$actionName] = array(
246       'withLayout'     => isset($options['withLayout']) ? $options['withLayout'] : false,
247       'lifeTime'       => $options['lifeTime'],
248       'clientLifeTime' => isset($options['clientLifeTime']) ? $options['clientLifeTime'] : $options['lifeTime'],
249       'contextual'     => isset($options['contextual']) ? $options['contextual'] : false,
250       'vary'           => isset($options['vary']) ? $options['vary'] : array(),
251     );
252   }
253
254   /**
255    * Registers configuration options for the cache.
256    *
257    * @param string $moduleName  Module name
258    */
259   public function registerConfiguration($moduleName)
260   {
261     if (!isset($this->loaded[$moduleName]))
262     {
263       require($this->context->getConfigCache()->checkConfig('modules/'.$moduleName.'/config/cache.yml'));
264       $this->loaded[$moduleName] = true;
265     }
266   }
267
268   /**
269    * Retrieves the layout from the cache option list.
270    *
271    * @param  string $internalUri  Internal uniform resource identifier
272    *
273    * @return bool true, if have layout otherwise false
274    */
275   public function withLayout($internalUri)
276   {
277     return $this->getCacheConfig($internalUri, 'withLayout', false);
278   }
279
280   /**
281    * Retrieves lifetime from the cache option list.
282    *
283    * @param  string $internalUri  Internal uniform resource identifier
284    *
285    * @return int LifeTime
286    */
287   public function getLifeTime($internalUri)
288   {
289     return $this->getCacheConfig($internalUri, 'lifeTime', 0);
290   }
291
292   /**
293    * Retrieves client lifetime from the cache option list
294    *
295    * @param  string $internalUri  Internal uniform resource identifier
296    *
297    * @return int Client lifetime
298    */
299   public function getClientLifeTime($internalUri)
300   {
301     return $this->getCacheConfig($internalUri, 'clientLifeTime', 0);
302   }
303
304   /**
305    * Retrieves contextual option from the cache option list.
306    *
307    * @param  string $internalUri  Internal uniform resource identifier
308    *
309    * @return boolean true, if is contextual otherwise false
310    */
311   public function isContextual($internalUri)
312   {
313     return $this->getCacheConfig($internalUri, 'contextual', false);
314   }
315
316   /**
317    * Retrieves vary option from the cache option list.
318    *
319    * @param  string $internalUri  Internal uniform resource identifier
320    *
321    * @return array Vary options for the cache
322    */
323   public function getVary($internalUri)
324   {
325     return $this->getCacheConfig($internalUri, 'vary', array());
326   }
327
328   /**
329    * Gets a config option from the cache.
330    *
331    * @param string $internalUri   Internal uniform resource identifier
332    * @param string $key           Option name
333    * @param string $defaultValue  Default value of the option
334    *
335    * @return mixed Value of the option
336    */
337   protected function getCacheConfig($internalUri, $key, $defaultValue = null)
338   {
339     list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
340
341     $this->registerConfiguration($params['module']);
342
343     $value = $defaultValue;
344     if (isset($this->cacheConfig[$params['module']][$params['action']][$key]))
345     {
346       $value = $this->cacheConfig[$params['module']][$params['action']][$key];
347     }
348     else if (isset($this->cacheConfig[$params['module']]['DEFAULT'][$key]))
349     {
350       $value = $this->cacheConfig[$params['module']]['DEFAULT'][$key];
351     }
352
353     return $value;
354   }
355
356   /**
357    * Returns true if the current content is cacheable.
358    *
359    * Possible break in backward compatibility: If the sf_lazy_cache_key
360    * setting is turned on in settings.yml, this method is not used when
361    * initially checking a partial's cacheability.
362    *
363    * @see sfPartialView, isActionCacheable()
364    *
365    * @param  string $internalUri  Internal uniform resource identifier
366    *
367    * @return bool true, if the content is cacheable otherwise false
368    */
369   public function isCacheable($internalUri)
370   {
371     if (count($_GET) || count($_POST))
372     {
373       return false;
374     }
375
376     list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
377
378     $this->registerConfiguration($params['module']);
379
380     if (isset($this->cacheConfig[$params['module']][$params['action']]))
381     {
382       return ($this->cacheConfig[$params['module']][$params['action']]['lifeTime'] > 0);
383     }
384     else if (isset($this->cacheConfig[$params['module']]['DEFAULT']))
385     {
386       return ($this->cacheConfig[$params['module']]['DEFAULT']['lifeTime'] > 0);
387     }
388
389     return false;
390   }
391
392   /**
393    * Returns true if the action is cacheable.
394    *
395    * @param  string $moduleName A module name
396    * @param  string $actionName An action or partial template name
397    *
398    * @return boolean True if the action is cacheable
399    *
400    * @see isCacheable()
401    */
402   public function isActionCacheable($moduleName, $actionName)
403   {
404     if (count($_GET) || count($_POST))
405     {
406       return false;
407     }
408
409     $this->registerConfiguration($moduleName);
410
411     if (isset($this->cacheConfig[$moduleName][$actionName]))
412     {
413       return $this->cacheConfig[$moduleName][$actionName]['lifeTime'] > 0;
414     }
415     else if (isset($this->cacheConfig[$moduleName]['DEFAULT']))
416     {
417       return $this->cacheConfig[$moduleName]['DEFAULT']['lifeTime'] > 0;
418     }
419
420     return false;
421   }
422
423   /**
424    * Retrieves content in the cache.
425    *
426    * @param  string $internalUri  Internal uniform resource identifier
427    *
428    * @return string The content in the cache
429    */
430   public function get($internalUri)
431   {
432     // no cache or no cache set for this action
433     if (!$this->isCacheable($internalUri) || $this->ignore())
434     {
435       return null;
436     }
437
438     $retval = $this->cache->get($this->generateCacheKey($internalUri));
439
440     if (sfConfig::get('sf_logging_enabled'))
441     {
442       $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Cache for "%s" %s', $internalUri, $retval !== null ? 'exists' : 'does not exist'))));
443     }
444
445     return $retval;
446   }
447
448   /**
449    * Returns true if there is a cache.
450    *
451    * @param  string $internalUri  Internal uniform resource identifier
452    *
453    * @return bool true, if there is a cache otherwise false
454    */
455   public function has($internalUri)
456   {
457     if (!$this->isCacheable($internalUri) || $this->ignore())
458     {
459       return null;
460     }
461
462     return $this->cache->has($this->generateCacheKey($internalUri));
463   }
464
465   /**
466    * Ignores the cache functionality.
467    *
468    * @return bool true, if the cache is ignore otherwise false
469    */
470   protected function ignore()
471   {
472     // ignore cache parameter? (only available in debug mode)
473     if (sfConfig::get('sf_debug') && $this->context->getRequest()->getAttribute('_sf_ignore_cache'))
474     {
475       if (sfConfig::get('sf_logging_enabled'))
476       {
477         $this->dispatcher->notify(new sfEvent($this, 'application.log', array('Discard cache')));
478       }
479
480       return true;
481     }
482
483     return false;
484   }
485
486   /**
487    * Sets the cache content.
488    *
489    * @param  string $data         Data to put in the cache
490    * @param  string $internalUri  Internal uniform resource identifier
491    *
492    * @return boolean true, if the data get set successfully otherwise false
493    */
494   public function set($data, $internalUri)
495   {
496     if (!$this->isCacheable($internalUri))
497     {
498       return false;
499     }
500
501     try
502     {
503       $ret = $this->cache->set($this->generateCacheKey($internalUri), $data, $this->getLifeTime($internalUri));
504     }
505     catch (Exception $e)
506     {
507       return false;
508     }
509
510     if (sfConfig::get('sf_logging_enabled'))
511     {
512       $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Save cache for "%s"', $internalUri))));
513     }
514
515     return true;
516   }
517
518   /**
519    * Removes the content in the cache.
520    *
521    * @param  string $internalUri       Internal uniform resource identifier
522    * @param  string $hostName          The host name
523    * @param  string $vary              The vary headers, separated by |, or "all" for all vary headers
524    * @param  string $contextualPrefix  The removal prefix for contextual partials. Defaults to '**' (all actions, all params)
525    *
526    * @return bool true, if the remove happened, false otherwise
527    */
528   public function remove($internalUri, $hostName = '', $vary = '', $contextualPrefix = '**')
529   {
530     if (sfConfig::get('sf_logging_enabled'))
531     {
532       $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Remove cache for "%s"', $internalUri))));
533     }
534
535     $cacheKey = $this->generateCacheKey($internalUri, $hostName, $vary, $contextualPrefix);
536
537     if(strpos($cacheKey, '*'))
538     {
539       return $this->cache->removePattern($cacheKey);
540     }
541     elseif ($this->cache->has($cacheKey))
542     {
543       return $this->cache->remove($cacheKey);
544     }
545   }
546
547   /**
548    * Retrieves the last modified time.
549    *
550    * @param  string $internalUri  Internal uniform resource identifier
551    *
552    * @return int    The last modified datetime
553    */
554   public function getLastModified($internalUri)
555   {
556     if (!$this->isCacheable($internalUri))
557     {
558       return 0;
559     }
560
561     return $this->cache->getLastModified($this->generateCacheKey($internalUri));
562   }
563
564   /**
565    * Retrieves the timeout.
566    *
567    * @param  string $internalUri  Internal uniform resource identifier
568    *
569    * @return int    The timeout datetime
570    */
571   public function getTimeout($internalUri)
572   {
573     if (!$this->isCacheable($internalUri))
574     {
575       return 0;
576     }
577
578     return $this->cache->getTimeout($this->generateCacheKey($internalUri));
579   }
580
581   /**
582    * Starts the fragment cache.
583    *
584    * @param  string $name            Unique fragment name
585    * @param  string $lifeTime        Life time for the cache
586    * @param  string $clientLifeTime  Client life time for the cache
587    * @param  array  $vary            Vary options for the cache
588    *
589    * @return bool true, if success otherwise false
590    */
591   public function start($name, $lifeTime, $clientLifeTime = null, $vary = array())
592   {
593     $internalUri = $this->routing->getCurrentInternalUri();
594
595     if (!$clientLifeTime)
596     {
597       $clientLifeTime = $lifeTime;
598     }
599
600     // add cache config to cache manager
601     list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
602     $this->addCache($params['module'], $params['action'], array('withLayout' => false, 'lifeTime' => $lifeTime, 'clientLifeTime' => $clientLifeTime, 'vary' => $vary));
603
604     // get data from cache if available
605     $data = $this->get($internalUri.(strpos($internalUri, '?') ? '&' : '?').'_sf_cache_key='.$name);
606     if ($data !== null)
607     {
608       return $data;
609     }
610     else
611     {
612       ob_start();
613       ob_implicit_flush(0);
614
615       return null;
616     }
617   }
618
619   /**
620    * Stops the fragment cache.
621    *
622    * @param  string $name Unique fragment name
623    *
624    * @return bool true, if success otherwise false
625    */
626   public function stop($name)
627   {
628     $data = ob_get_clean();
629
630     // save content to cache
631     $internalUri = $this->routing->getCurrentInternalUri();
632     try
633     {
634       $this->set($data, $internalUri.(strpos($internalUri, '?') ? '&' : '?').'_sf_cache_key='.$name);
635     }
636     catch (Exception $e)
637     {
638     }
639
640     return $data;
641   }
642
643   /**
644    * Computes the cache key based on the passed parameters.
645    *
646    * @param array $parameters  An array of parameters
647    */
648   public function computeCacheKey(array $parameters)
649   {
650     if (isset($parameters['sf_cache_key']))
651     {
652       return $parameters['sf_cache_key'];
653     }
654
655     if (sfConfig::get('sf_logging_enabled'))
656     {
657       $this->dispatcher->notify(new sfEvent($this, 'application.log', array('Generate cache key')));
658     }
659
660     return md5(serialize($parameters));
661   }
662
663   /**
664    * Checks that the supplied parameters include a cache key.
665    *
666    * If no 'sf_cache_key' parameter is present one is added to the array as
667    * it is passed by reference.
668    *
669    * @param  array  $parameters An array of parameters
670    *
671    * @return string The cache key
672    */
673   public function checkCacheKey(array & $parameters)
674   {
675     $parameters['sf_cache_key'] = $this->computeCacheKey($parameters);
676
677     return $parameters['sf_cache_key'];
678   }
679
680   /**
681    * Computes a partial internal URI.
682    *
683    * @param  string $module    The module name
684    * @param  string $action    The action name
685    * @param  string $cacheKey  The cache key
686    *
687    * @return string The internal URI
688    */
689   public function getPartialUri($module, $action, $cacheKey)
690   {
691     return sprintf('@sf_cache_partial?module=%s&action=%s&sf_cache_key=%s', $module, $action, $cacheKey);
692   }
693
694   /**
695    * Returns whether a partial template is in the cache.
696    *
697    * @param  string $module    The module name
698    * @param  string $action    The action name
699    * @param  string $cacheKey  The cache key
700    *
701    * @return bool true if a partial is in the cache, false otherwise
702    */
703   public function hasPartialCache($module, $action, $cacheKey)
704   {
705     return $this->has($this->getPartialUri($module, $action, $cacheKey));
706   }
707
708   /**
709    * Gets a partial template from the cache.
710    *
711    * @param  string $module    The module name
712    * @param  string $action    The action name
713    * @param  string $cacheKey  The cache key
714    *
715    * @return string The cache content
716    */
717   public function getPartialCache($module, $action, $cacheKey)
718   {
719     $uri = $this->getPartialUri($module, $action, $cacheKey);
720
721     if (!$this->isCacheable($uri))
722     {
723       return null;
724     }
725
726     // retrieve content from cache
727     $cache = $this->get($uri);
728
729     if (is_null($cache))
730     {
731       return null;
732     }
733
734     $cache = unserialize($cache);
735     $content = $cache['content'];
736     $this->context->getResponse()->merge($cache['response']);
737
738     if (sfConfig::get('sf_web_debug'))
739     {
740       $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $content)->getReturnValue();
741     }
742
743     return $content;
744   }
745
746   /**
747    * Sets an action template in the cache.
748    *
749    * @param  string $module    The module name
750    * @param  string $action    The action name
751    * @param  string $cacheKey  The cache key
752    * @param  string $content   The content to cache
753    *
754    * @return string The cached content
755    */
756   public function setPartialCache($module, $action, $cacheKey, $content)
757   {
758     $uri = $this->getPartialUri($module, $action, $cacheKey);
759     if (!$this->isCacheable($uri))
760     {
761       return $content;
762     }
763
764     $saved = $this->set(serialize(array('content' => $content, 'response' => $this->context->getResponse())), $uri);
765
766     if ($saved && sfConfig::get('sf_web_debug'))
767     {
768       $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $content)->getReturnValue();
769     }
770
771     return $content;
772   }
773
774   /**
775    * Returns whether an action template is in the cache.
776    *
777    * @param  string  $uri  The internal URI
778    *
779    * @return bool true if an action is in the cache, false otherwise
780    */
781   public function hasActionCache($uri)
782   {
783     return $this->has($uri) && !$this->withLayout($uri);
784   }
785
786   /**
787    * Gets an action template from the cache.
788    *
789    * @param  string $uri  The internal URI
790    *
791    * @return array  An array composed of the cached content and the view attribute holder
792    */
793   public function getActionCache($uri)
794   {
795     if (!$this->isCacheable($uri) || $this->withLayout($uri))
796     {
797       return null;
798     }
799
800     // retrieve content from cache
801     $cache = $this->get($uri);
802
803     if (is_null($cache))
804     {
805       return null;
806     }
807
808     $cache = unserialize($cache);
809     $content = $cache['content'];
810     $cache['response']->setEventDispatcher($this->dispatcher);
811     $this->context->getResponse()->copyProperties($cache['response']);
812
813     if (sfConfig::get('sf_web_debug'))
814     {
815       $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $content)->getReturnValue();
816     }
817
818     return array($content, $cache['decoratorTemplate']);
819   }
820
821   /**
822    * Sets an action template in the cache.
823    *
824    * @param  string $uri                The internal URI
825    * @param  string $content            The content to cache
826    * @param  string $decoratorTemplate  The view attribute holder to cache
827    *
828    * @return string The cached content
829    */
830   public function setActionCache($uri, $content, $decoratorTemplate)
831   {
832     if (!$this->isCacheable($uri) || $this->withLayout($uri))
833     {
834       return $content;
835     }
836
837     $saved = $this->set(serialize(array('content' => $content, 'decoratorTemplate' => $decoratorTemplate, 'response' => $this->context->getResponse())), $uri);
838
839     if ($saved && sfConfig::get('sf_web_debug'))
840     {
841       $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $content)->getReturnValue();
842     }
843
844     return $content;
845   }
846
847   /**
848    * Sets a page in the cache.
849    *
850    * @param string $uri  The internal URI
851    */
852   public function setPageCache($uri)
853   {
854     if (sfView::RENDER_CLIENT != $this->controller->getRenderMode())
855     {
856       return;
857     }
858
859     // save content in cache
860     $saved = $this->set(serialize($this->context->getResponse()), $uri);
861
862     if ($saved && sfConfig::get('sf_web_debug'))
863     {
864       $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $this->context->getResponse()->getContent())->getReturnValue();
865
866       $this->context->getResponse()->setContent($content);
867     }
868   }
869
870   /**
871    * Gets a page from the cache.
872    *
873    * @param  string $uri  The internal URI
874    *
875    * @return string The cached page
876    */
877   public function getPageCache($uri)
878   {
879     $retval = $this->get($uri);
880
881     if (is_null($retval))
882     {
883       return false;
884     }
885
886     $cachedResponse = unserialize($retval);
887     $cachedResponse->setEventDispatcher($this->dispatcher);
888
889     if (sfView::RENDER_VAR == $this->controller->getRenderMode())
890     {
891       $this->controller->getActionStack()->getLastEntry()->setPresentation($cachedResponse->getContent());
892       $this->response->setContent('');
893     }
894     else
895     {
896       $this->context->setResponse($cachedResponse);
897
898       if (sfConfig::get('sf_web_debug'))
899       {
900         $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $this->context->getResponse()->getContent())->getReturnValue();
901
902         $this->context->getResponse()->setContent($content);
903       }
904     }
905
906     return true;
907   }
908 }
909
Note: See TracBrowser for help on using the browser.