Skip to content

Instantly share code, notes, and snippets.

@formigone
Created December 17, 2014 16:48
Show Gist options
  • Save formigone/bc4e9afe14c084037e7c to your computer and use it in GitHub Desktop.
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
<?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