Last active
August 29, 2015 14:26
-
-
Save Loupax/87dfc027f4dd9dcc374d to your computer and use it in GitHub Desktop.
Cache class for PHP
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 | |
| class Cache { | |
| private $cache = []; | |
| public function functionCall($callable, $params = []){ | |
| $hash = serialize([$callable, $params]); | |
| if(!isset($this->cache[$hash])){ | |
| $this->cache[$hash] = call_user_func_array($callable, $params); | |
| echo "Function called!\t"; | |
| }else{ | |
| echo "Cached result returned.\t"; | |
| } | |
| return $this->cache[$hash]; | |
| } | |
| } | |
| // Tests for the caching functionality | |
| $cache = new Cache(); | |
| function test($a, $b){ | |
| sleep(1); | |
| return $a + $b; | |
| } | |
| echo $cache->functionCall('test', [1,1])."\n"; | |
| echo $cache->functionCall('test', [1,2])."\n"; | |
| echo $cache->functionCall('test', [1,3])."\n"; | |
| echo $cache->functionCall('test', [1,1])."\n"; | |
| class Foo { | |
| public static function sum($a, $b){ | |
| sleep(1); | |
| return $a + $b; | |
| } | |
| public function otherSum($a, $b){ | |
| sleep(1); | |
| return $a + $b; | |
| } | |
| } | |
| // Static call test | |
| echo $cache->functionCall(['Foo', 'sum'], [1,1])."\n"; | |
| echo $cache->functionCall(['Foo', 'sum'], [1,2])."\n"; | |
| echo $cache->functionCall(['Foo', 'sum'], [1,3])."\n"; | |
| echo $cache->functionCall(['Foo', 'sum'], [1,1])."\n"; | |
| // Object call test | |
| $foo = new Foo; | |
| echo $cache->functionCall([$foo, 'otherSum'], [1,1])."\n"; | |
| echo $cache->functionCall([$foo, 'otherSum'], [1,2])."\n"; | |
| echo $cache->functionCall([$foo, 'otherSum'], [1,3])."\n"; | |
| echo $cache->functionCall([$foo, 'otherSum'], [1,1])."\n"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment