Created
July 10, 2017 10:24
-
-
Save alrik11es/d68421d437defd889f28cee643640bf7 to your computer and use it in GitHub Desktop.
Saves methods result on memory. Needs to be private or protected to work. Public methods will never be saved in memory.
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 | |
namespace App; | |
trait Memorize | |
{ | |
/** | |
* @var array [method][parameters] | |
*/ | |
private $memorizedResults = []; | |
protected function memorizedCall($methodName, $args = null) | |
{ | |
$serializedArgs = md5(\serialize($args)); | |
if (! isset($this->memorizedResults[$methodName][$serializedArgs])) { | |
$this->memorizedResults[$methodName][$serializedArgs] = $this->$methodName(...$args); | |
} | |
return $this->memorizedResults[$methodName][$serializedArgs]; | |
} | |
public function __call($name, $args) | |
{ | |
return $this->memorizedCall($name, $args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment