Created
March 18, 2015 15:18
-
-
Save proudlygeek/9579c2ec693d689e9036 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| // You can use an abstract class as well | |
| trait Cachable { | |
| private $cache = []; | |
| public function cached($method, $args) { | |
| echo "[Cache] Called $method\n"; | |
| if (!isset($this->cache[$method])) { | |
| echo "[Cache] Saving method in cache\n"; | |
| $this->cache[$method] = $this->$method($args); | |
| } | |
| echo $this->cache[$method]; | |
| } | |
| } | |
| abstract class Model { | |
| public function __call($method, $args) | |
| { | |
| $origMethod = preg_replace('/cached/', '', $method); | |
| if (preg_match('/cached.*/', $method) && | |
| array_key_exists('Cachable', class_uses(get_class($this)))) { | |
| return $this->cached($origMethod, $args); | |
| } else { | |
| return $this->$origMethod($args); | |
| } | |
| } | |
| } | |
| class MyModel extends Model { | |
| use Cachable; | |
| public function getSlowQueryResults() | |
| { | |
| // Long operation | |
| return "[Result] Very long result...\n"; | |
| } | |
| } | |
| $model = new MyModel(); | |
| echo $model->cachedGetSlowQueryResults(); | |
| echo $model->cachedGetSlowQueryResults(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment