如何将DI容器注入控制器?

时间:2019-05-11 09:52:15

标签: php

我已经使用PHP-DI成功安装了路由器。 有一些基于app example的简单article

有2个文件:index.php和controller.php。我想使用控制器中的$ container。但是,我不知道该如何注射?

// index.php 

use... 
require_once... 

$containerBuilder = new ContainerBuilder(); 
.... 
$container = $containerBuilder->build(); // I succesfuilly build a container here with all needed definitions, including Database, Classes and so on. 

$routes = simpleDispatcher(function (RouteCollector $r) {
    $r->get('/hello', Controller::class);
});
$middlewareQueue[] = new FastRoute($routes);
$middlewareQueue[] = new RequestHandler($container);

$requestHandler = new Relay($middlewareQueue);
$response = $requestHandler->handle(ServerRequestFactory::fromGlobals());

$emitter = new SapiEmitter();
return $emitter->emit($response);

因此,代码仅从调度程序接收响应,并将其传递给发射器。

namespace ExampleApp;
use Psr\Http\Message\ResponseInterface;

class Controller
{
    private $foo;
    private $response;

    public function __construct(
        string $foo,
        ResponseInterface $response
    ) {
        $this->foo = $foo;
        $this->response = $response;
    }

    public function __invoke(): ResponseInterface
    {
        $response = $this->response->withHeader('Content-Type', 'text/html');
        $response->getBody()
            ->write("<html><head></head><body>Hello, {$this->foo} world!</body></html>");

        return $response;
    }
}

现在,我想基于$ container将逻辑添加到Controller中:数据库,记录器等。我想以某种方式使用在index.php中创建的$ container实例。我已经尝试了很多方法,但是没有任何正常工作。

0 个答案:

没有答案