PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Do you want DIC with that Controller?

Note: This article was originally published at Planet PHP on 20 April 8500.
Planet PHP

At Liip "Symfony2" started in production a year earlier. Well I say "Symfony2" because it was just our internal framework OkAPI enhanced with the current crop of at the time PHP 5.2 Symfony components (actually we also included the symfony 1.x routing component). The results were so convincing that we decided to switch to Symfony2 entirely. The big feature back then and today is of course dependency injection (DI) and the dependency injection container (DIC). I remember many discussion with Jordi back then, where we went back and forth on if Controllers should be configured in the DIC or not. In the end we did go with making Controllers DIC services. The other alternative is of course to instead just inject the entire DIC and let the Controller pull whatever services it needs straight from the DIC.

Just to make it clear what we are talking about, here is an example without using a service:

class HelloController implements ContainerAwareInterface { protected $container; public function setContainer(ContainerInterface $container) { $this-container = $container; } public function indexAction($name) { $template = 'LiipHelloBundle:Hello:index.html.twig'; $params = array('name' = $name); return $this-container-get('templating')-render($template, $params); } } ?

And here with a service:

// requires the following service definition: // services: // liip_hello.world.controller: // class: Liip\HelloBundle\Controller\HelloController // arguments: // -@templating class HelloController { protected $templating; public function __construct(EngineInterface $templating) { $this-templating = $templating; } public function indexAction($name) { $template = 'LiipHelloBundle:Hello:index.html.twig'; $params = array('name' = $name); return

Truncated by Planet PHP, read more at the original (another 4273 bytes)