Symfony3 controller constructor injection is not working

When using the base classController.php the Container is usually auto-wired by the framework in theControllerResolver.

Basically you are trying to mix up how things actually work.

To solve your problem you basically have two solutions:

  1. Do no try to inject the dependency but fetch it directly from the Container from within your action/method.

public function listUsers(Request $request) { $em = $this->container->get('doctrine.orm.entity_manager'); }

  1. Create a controller manually but not extend the Controller base class; and set ip up as a service

To go a bit further on this point, some people will advise to do not use the default Controller provided by Symfony.

While I totally understand their point of view, I'm slightly more moderated on the subject.

The idea behind injecting only the required dependencies is to avoid and force people to have thin controller, which is a good thing.

However, with a little of auto-determination, using the existing shortcut is much simpler.

A Controller / Action is nothing more but the glue between your Views and your Domain/Models.

Prevent yourself from doing too much in your Controller using the ContainerAware facility.

A Controller can thrown away without generate business changes in your system.


Since 2017 and Symfony 3.3+, there is native support for controllers as services.

You can keep your controller the way it is, since you're using constructor injection correctly.

Just modify your services.yml:

# app/config/services.yml

services:
    _defaults:
        autowire: true

    AppBundle\:
        resouces: ../../src/AppBundle

It will:

  • load all controllers and repositories as services
  • autowire contructor dependencies (in your case EntityManager)


Step further: repositories as services

Ther were many question on SO regarding Doctrine + repository + service + controller, so I've put down one general answer to a post. Definitelly check if you prefer constructor injection and services over static and service locators.

Tags:

Php

Symfony