php - 如何将 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 实例。我已经尝试了很多方法,但没有一个能正常工作。
解决方案
推荐阅读
- c# - 带有 SignalR 和动态 DNS 解析的 NGINX 反向代理
- java - 投射到另一个对象时出现Classcastexception,目前正在使用power mockito进行测试?
- php - laravel,为任务调度创建心跳
- python - Amazon lex 不保存未定义的自定义槽值
- python - 如何在python中将变量移到函数之外
- spring-boot - 我正在尝试对我的 springBoot 控制器进行单元测试。但我似乎找不到如何检查参数是否正确
- c# - 多个 Npsql 连接
- spring - 当使用 git 和 redis 作为后端的组合时,Spring 云配置服务器不从 redis 读取属性
- postgresql - PostgreSQL - 查询多维数组
- powershell - 如何在powershell中检查日期格式