首页 > 解决方案 > 如何将 DI 容器注入控制器?

问题描述

我已经使用PHP-DI成功安装了路由器。有一些基于文章的简单应用示例

有 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 实例。我已经尝试了很多方法,但没有一个能正常工作。

标签: php

解决方案


推荐阅读