Last active
August 29, 2015 14:17
-
-
Save proudlygeek/88835c43aab6266e1e76 to your computer and use it in GitHub Desktop.
PHP Cache Trait
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 | |
| 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]; | |
| } | |
| } | |
| class MyModel { | |
| use Cachable; | |
| public function getSlowQueryResults() | |
| { | |
| // Long operation | |
| return "[Result] Very long result...\n"; | |
| } | |
| public function foo() | |
| { | |
| print_r($this->cache); | |
| } | |
| } | |
| $model = new MyModel(); | |
| echo $model->cached('getSlowQueryResults', []); | |
| echo $model->cached('getSlowQueryResults', []); | |
| $model->foo(); | |
| $model->getSlowQueryResult(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment