Skip to content

Instantly share code, notes, and snippets.

@shadowhand
Last active November 18, 2016 17:54
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 shadowhand/cf54cd615a6f18e64e9264429008f980 to your computer and use it in GitHub Desktop.
Save shadowhand/cf54cd615a6f18e64e9264429008f980 to your computer and use it in GitHub Desktop.
Execute any method, static or instance, as a callable
<?php
namespace Acme;
class NamedCallable
{
private $invoke;
private $prefix;
public function __construct(callable $invoke, callable $prefix)
{
$this->invoke = $invoke;
$this->prefix = $prefix;
}
public function make($spec)
{
return function ($args) use ($spec) {
$args = array_combine(
// Prefix the keys of the args if required
array_map($this->prefix, array_keys($args)),
$args
);
// Invoke with spec and args
return call_user_func($this->invoke, $spec, $args);
};
}
}
<?php
require __DIR__ . '/../vendor/autoload.php';
class Hello
{
public function user($name)
{
echo 'Hello, ', $name, '!';
}
}
use Acme\NamedCallable;
use Auryn\Injector;
$injector = new Injector;
$invoke = [$injector, 'execute'];
$prefix = function ($key) {
return ':' . $key;
};
$factory = new NamedCallable($invoke, $prefix);
$callable = $factory->make('Hello::user');
call_user_func($callable, ['name' => 'John']);
@shadowhand
Copy link
Author

This is particularly useful with fast-route, which generates named parameters (as a hash) from route matching.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment