phpsymfonydependency-injectionsymfony-components

Standalone Symfony DIC in my controllers


I'm using Symfony DIC, Routing and ControllerResolver in my project following Create your own PHP Framework

I do not understand how I can correctly transfer services to the constructor of my controller without using the Config Component or set container in the controller? Routing:

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

Controller:

    class MyController implements ContainerAwareInterface
    {
        use ContainerAwareTrait;

        protected $entityManager;

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

        public function indexAction()
        {
            ...
        }
   }

Container and handle:

$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();

Solution

  • I found the answer here https://stackoverflow.com/a/23956418/8328328.

    So without overriding Controller Resolver can not do.