Code snippets for symfony 1.x

Navigation

Snippets by user Štěpán Ulver

function/method cache

My alternative for sfFunctionCache, which can work with objects/classes. Useful for caching external data, like rss feeds etc.

class myFunctionCache extends sfFileCache
{
  public function __construct($dir=null)
  {
    if (is_null($dir)) $dir = SF_ROOT_DIR.'/cache/'.SF_APP.'/function';
    parent::__construct($dir);
  }
  public function call ()
  {
    $arguments = func_get_args();
 
    // check if first argument is array (object/class function call)
    if (is_array($arguments[0])) $id = md5(serialize(array_merge(array(0=>$arguments[0][1], 1=>(is_object($arguments[0][0]) ? get_class($arguments[0][0]) : $arguments[0][0]), array_slice($arguments_serialize=$arguments, 1)))));
    else $id = md5(serialize($arguments));
 
    $data = $this->get($id);
    if ($data !== null)
    {
      $array = unserialize($data);
      $output = $array['output'];
      $result = $array['result'];
    }
    else
    {
      $target = array_shift($arguments);
      ob_start();
      ob_implicit_flush(false);
      $result = call_user_func_array($target, $arguments);
      $output = ob_get_clean();
      $this->set($id, '', serialize(array('output'=>$output, 'result'=>$result)));
    }
 
    if (!empty($output)) echo($output);
    return $result;
  }        
}

In action:

$cache = new myFunctionCache();
$rss_items = $cache->call(array(&$rss, 'getItems'), 'http://www.symfony-project.com/weblog/rss');
by Štěpán Ulver on 2006-10-03, tagged cache 
(1 comment)