我的控制器中的独立Symfony DIC

时间:2017-08-26 12:17:39

标签: php symfony dependency-injection symfony-components

我在Create your own PHP Framework之后的项目中使用了Symfony DIC,Routing和ControllerResolver

我不明白如何在不使用配置组件或在控制器中设置容器的情况下将服务正确地传输到控制器的构造函数? 路由:

$routes->add('mycontroller', new Routing\Route('/', ['_controller' => 'controller.mycontroller::indexAction']));

控制器:

    class MyController implements ContainerAwareInterface
    {
        use ContainerAwareTrait;

        protected $entityManager;

        public function __construct(Doctrine $doctrine)
        {
            $this->entityManager = $doctrine->entityManager;
        }

        public function indexAction()
        {
            ...
        }
   }

容器和句柄:

$container = new DependencyInjection\ContainerBuilder();
$container->register('context', Routing\RequestContext::class);
$container->register('matcher', Routing\Matcher\UrlMatcher::class)
             ->setArguments([$routes, new Reference('context')]);
$container->register('doctrine', Doctrine::class)
             ->setArguments($db);
...
$container->register('controller.mycontroller',MyController::class)
             ->setArguments([new Reference('doctrine')]);

$request = Request::createFromGlobals();

/**
 * @var \Symfony\Component\HttpKernel\HttpKernel $kernel
 */
$kernel = $container->get('base');
/**
 * @var \Symfony\Component\HttpFoundation\Response $response
 */
$response = $kernel->handle($request);

$response->send();

1 个答案:

答案 0 :(得分:0)

我在这里找到了答案https://stackoverflow.com/a/23956418/8328328

因此,如果没有覆盖Controller Resolver就无法做到。