Skip to content

Instantly share code, notes, and snippets.

@alrik11es
Created July 10, 2017 10:24
Show Gist options
  • Save alrik11es/d68421d437defd889f28cee643640bf7 to your computer and use it in GitHub Desktop.
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.
<?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