Skip to content

Instantly share code, notes, and snippets.

@Mikulas
Created November 27, 2010 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mikulas/717781 to your computer and use it in GitHub Desktop.
Save Mikulas/717781 to your computer and use it in GitHub Desktop.
Magic call to cached functions
<?php
const CACHED_PREFIX = 'c_';
/**
* Call to cached or undefined method.
* @param string method name
* @param array arguments
* @return mixed
* @throws \MemberAccessException
* @throws \InvalidStateException
*/
public function __call($name, $args)
{
if (!\Nette\String::startsWith($name, self::CACHED_PREFIX)) {
return ObjectMixin::call($this, $name, $args);
}
$method = substr($name, strlen(self::CACHED_PREFIX));
if (!$this->reflection->hasMethod($method))
{
throw new \InvalidStateException('Invalid call for cached output of ' . $this->reflection->name . '::' . $method . ', method not set.');
}
$reflection = new \Nette\Reflection\MethodReflection($this, $method);
$ann = $reflection->getAnnotation('cache');
$cache = \Nette\Environment::getCache('method');
$key = $this->reflection->name . '::' . $name . '?' . md5(serialize($args));
if (!isset($cache[$key])) {
$cache[$key] = $reflection->invokeArgs($this, $args);
$depends = array();
if (is_array($ann)) {
foreach($ann as $index => $value) {
$const = constant('\Nette\Caching\Cache::' . strtoupper($index));
if ($const) {
$depends += array($const => $value);
} else {
throw new \InvalidArgumentException('Invalid cache options set for `' . $key . '`, dependency on `' . $index . '` not found.');
}
}
}
$cache->save($key, $reflection->invoke($this, $args), $depends);
}
return $cache[$key];
}
@Mikulas
Copy link
Author

Mikulas commented Nov 27, 2010

public function test()
{
    return rand(10e3, 10e4);
}

or
/**
* @cache
/
public function test()
{
return rand(10e3, 10e4);
}
or
/
*
* @cache(expire=3600)
*/
public function test()
{
return rand(10e3, 10e4);
}

call with caching:

$obj->c_test();

call without caching:

$obj->test();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment