Last active
November 18, 2016 17:54
-
-
Save shadowhand/cf54cd615a6f18e64e9264429008f980 to your computer and use it in GitHub Desktop.
Execute any method, static or instance, as a callable
This file contains 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 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); | |
}; | |
} | |
} |
This file contains 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 | |
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']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is particularly useful with fast-route, which generates named parameters (as a hash) from route matching.