我已经开始使用PHP-DI
来管理自定义CMS的某些依赖项注入。它与将管理路由的FastRoute集成在一起(我已经开始编写自己的路由系统,但现在太穷了,无法在生产中使用)。我需要注入将主要使用静态方法的RedBeanPHP实例。阅读文档后,我无法达到范围,有什么方法可以完成此任务吗?
<?php
require_once __DIR__.'/vendor/autoload.php';
use \RedBeanPHP\R;
// Thi part of code is taken from the docs of FastRoute on github
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $router) {
$router->addRoute('GET', '/', 'Controller/index');
/* User uri mapping */
$router->addGroup('/user' , function(FastRoute\RouteCollector $router){
$router->addRoute('GET', '/', 'UserController/index');
$router->addRoute('POST', '/doRegistration', 'UserController/register');
});
});
// Fetch method and URI from somewhere
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
// Strip query string (?foo=bar) and decode URI
if(false !== $pos = strpos($uri, '?')){
$uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::NOT_FOUND:
// ... 404 Not Found
break;
case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
$allowedMethods = $routeInfo[1];
// ... 405 Method Not Allowed
break;
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
list($class, $method) = explode("/", $handler, 2);
// dependency injection
$container = new DI\Container();
$redBean = $container->call('RedBeanPHP\R');
$container->get($redBean);
call_user_func_array([new $class, $method], $vars);
break;
}