Created
November 27, 2010 10:43
-
-
Save Mikulas/717781 to your computer and use it in GitHub Desktop.
Magic call to cached functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
or
/**
* @cache
/
public function test()
{
return rand(10e3, 10e4);
}
or
/*
* @cache(expire=3600)
*/
public function test()
{
return rand(10e3, 10e4);
}
call with caching:
call without caching: