我在创建您自己的 PHP 框架 ( https://symfony.com/doc/current/create_framework/index.html ) 之后在我的项目中使用 Symfony DI、Http、内核、路由。使用 is_leap_year App 演示目的没问题。
我试图弄清楚如何将服务和容器注入到仅使用 Symfony 组件而不是框架包的路由中定义的自定义控制器中。
容器.php
// add demo service into the service container
$containerBuilder->register('demo.service', '\Demo\DemoService');
// add dependent service into the controller container
$containerBuilder->register('dependent.controller', '\Demo\DemoController')
->setArguments([new Reference('demo.service')]);
// fetch service from the service container
// Echoing Works fine! But no service in controller
//echo $containerBuilder->get('dependent.controller')->helloWorld();
应用程序.php
// nok with dependency
$routes->add('hello', new Routing\Route('/hello', [
'_controller' => 'Demo\DemoController::helloWorld',
]));
// ok with no dependency
$routes->add('hello2', new Routing\Route('/hello2', [
'_controller' => 'Demo\DemoService::helloWorld',
]));
和 DemoController.php
<?php declare(strict_types=1);
namespace Demo;
class DemoController
{
private $demo_service;
public function __construct(\Demo\DemoService $demoService)
{
$this->demo_service = $demoService;
}
public function helloWorld()
{
return $this->demo_service->helloWorld();
}
}
退货
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Demo\DemoController::__construct(), 0 passed
我怎样才能得到这个工作?或者,我如何将容器注入控制器构造函数?