1. sfFunctionCache.class.php
  2. /** * This class can be used to cache the result and output of any PHP callable (function and method calls). * * @package symfony * @subpackage cache * @author Fabien Potencier * @version SVN: $Id: sfFunctionCache.class.php 23939 2009-11-14 17:46:14Z fabien $ */
  3. class sfFunctionCache
  4. {
  5. protected $cache = null;
  6. /**
  7. * Constructor.
  8. *
  9. * @param sfCache $cache An sfCache object instance
  10. */
  11. public function __construct(sfCache $cache)
  12. {
  13. $this->cache = $cache;
  14. }
  15. /**
  16. * Calls a cacheable function or method (or not if there is already a cache for it).
  17. *
  18. * Arguments of this method are read with func_get_args. So it doesn't appear in the function definition.
  19. *
  20. * The first argument can be any PHP callable:
  21. *
  22. * $cache->call('functionName', array($arg1, $arg2));
  23. * $cache->call(array($object, 'methodName'), array($arg1, $arg2));
  24. *
  25. * @param mixed $callable A PHP callable
  26. * @param array $arguments An array of arguments to pass to the callable
  27. *
  28. * @return mixed The result of the function/method
  29. */
  30. public function call($callable, $arguments = array())
  31. {
  32. // Generate a cache id
  33. $key = $this->computeCacheKey($callable, $arguments);
  34. $serialized = $this->cache->get($key);
  35. if ($serialized !== null)
  36. {
  37. $data = unserialize($serialized);
  38. }
  39. else
  40. {
  41. $data = array();
  42. if (!is_callable($callable))
  43. {
  44. throw new sfException('The first argument to call() must be a valid callable.');
  45. }
  46. ob_start();
  47. ob_implicit_flush(false);
  48. try
  49. {
  50. $data['result'] = call_user_func_array($callable, $arguments);
  51. }
  52. catch (Exception $e)
  53. {
  54. ob_end_clean();
  55. throw $e;
  56. }
  57. $data['output'] = ob_get_clean();
  58. $this->cache->set($key, serialize($data));
  59. }
  60. echo $data['output'];
  61. return $data['result'];
  62. }
  63. /**
  64. * Returns the cache instance.
  65. *
  66. * @return sfCache The sfCache instance
  67. */
  68. public function getCache()
  69. {
  70. return $this->cache;
  71. }
  72. /**
  73. * Computes the cache key for a given callable and the arguments.
  74. *
  75. * @param mixed $callable A PHP callable
  76. * @param array $arguments An array of arguments to pass to the callable
  77. *
  78. * @return string The associated cache key
  79. */
  80. public function computeCacheKey($callable, $arguments = array())
  81. {
  82. return md5(serialize($callable).serialize($arguments));
  83. }
  84. }

Debug toolbar