6

There are some articles around which touch this topic, but none of them seemed to be a practical usable solution for me. My goal is to put some basic methods (those I need in each controller anyway) into a basecontroller, e.g.

   $this->getEntityManager();
   $this->getRequest();
   $this->getRepository($entityName);

How can this be done?

AFAIK we have to inject the services into the basecontroller, but how do I tell classes to use a service for their superclass? There is some decent article about Controllers and Dependency Injection [1], but finally I got stuck with that approach too, see my comment here: [2]

[1] http://miller.limethinking.co.uk/2011/04/15/symfony2-controller-as-service/

[2] http://miller.limethinking.co.uk/2011/04/15/symfony2-controller-as-service/#comment-579

1 Answer 1

3

pseudocode

MyBaseController impliments Symfony\Component\Di\ContainerAwareInterface
  setContainer($container)
    $this->container = $container

  getEntityManager
    return $this->container->get('doctrine.orm.entity_manager')
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the hint. When I make use of the basecontroller i get following error message: "Fatal error: Declaration of ...Bundle\Controller\BaseController::setContainer() must be compatible with that of Symfony\Component\DependencyInjection\ContainerAwareInterface::setContainer() in /Library/WebServer/Documents/...Bundle/Controller/BaseController.php on line 9". Setter looks like this: function setContainer(\Symfony\Component\DependencyInjection\ContainerInterface $container){ $this->container = $container; }
$container can be null, so should be (...\ContainerInterface$container = null)
BAD IDEA. It's like loading everything and saying it's lean. I suggest you simply do an abstract class MyBaseController with protected methods. But do not inject all stuff like this. See "problematic"'s post series "Controller in a diet" it explains A LOT.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.