Created
December 17, 2014 16:48
-
-
Save formigone/bc4e9afe14c084037e7c to your computer and use it in GitHub Desktop.
Idea for a dependency injection service similar to Angular.js, but for handler function-based PHP routers like Slim Framework
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 | |
/** | |
* Class Handler | |
* | |
* Playing around with reflection & DI. Handler is a routing class (think Express [node.js] or Slim [php]), | |
* with a built-in dependency injection system inspired by Angular.js. | |
* | |
* Consider this: | |
* - Use annotations in the handler callback to specify what class needs to be instantiated? | |
* - Use annotations to specify a 'key' that some DI framework that Handler bundles can use to build dep? | |
* - Depend solely on the arg name to match a class? | |
* - But what if a class is namespaced => \App\Service\User? | |
*/ | |
class Handler { | |
protected $inj = []; | |
public function __construct() { | |
$this->inj['time'] = function(){ | |
return time(); | |
}; | |
} | |
public function doit($cb) { | |
$ref = new ReflectionFunction($cb); | |
$c = $ref->getParameters(); | |
// Fake deps resolution => if param name matches 'configured key' in $this->inj => build dep. Else, return as str | |
$args = array_map(function($arg){ | |
$arg = $arg->name; | |
if (array_key_exists($arg, $this->inj)) { | |
return $this->inj[$arg](); | |
} else { | |
return $arg; | |
} | |
}, $c); | |
return call_user_func_array($cb, $args); | |
} | |
} | |
$h = new Handler(); | |
$h->doit(function($time, $hello, $world){ | |
echo date('Y-m-d H:i:s', $time). ' ==> '. $hello. ', '. $world; | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment