Skip to content

Instantly share code, notes, and snippets.

@ngoylufo
Last active December 9, 2020 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngoylufo/3c1e9257dfeec3c152dba1d1e1de2fdb to your computer and use it in GitHub Desktop.
Save ngoylufo/3c1e9257dfeec3c152dba1d1e1de2fdb to your computer and use it in GitHub Desktop.
<?php
class Label
{
private $label;
public function __construct(string $label)
{
$this->label = $label;
}
public function getText(): string
{
return $this->label;
}
}
function pluralizeLabel(Label $label): string
{
$entries = [
'angle' => ['singular' => 'angle', 'plural' => 'angles'],
'issue' => ['singular' => 'issue', 'plural' => 'issues']
];
echo "Reading from database. \n";
$text = strtolower($label->getText());
return $entries[$text]['plural'];
}
function memoize(callable $fn, callable $serialize = null): callable
{
$serialize = $serialize ?: 'serialize';
return function (...$args) use ($fn, $serialize) {
static $cache = [];
$key = $serialize($args);
return $cache[$key] ?? ($cache[$key] = $fn(...$args));
};
}
// Example
$issue = new Label('Issue');
// use the closure instead of serialize to get the key.
$pluralize = memoize('pluralizeLabel', function(array $args) {
$label = $args[0];
return $label->getText();
});
// connects to the database, finds record, returns plural.
echo "First call: \n";
echo $pluralize($issue) . "\n\n"; // => issues
// Gets the value from the cache instead
echo "Second call: \n";
echo $pluralize($issue) . "\n\n"; // => issues
// Gets the value from the cache instead
echo "Third call: \n";
echo $pluralize($issue) . "\n\n"; // => issues
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment