Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Base-Controller Class which implements the ContainerAwareInterface

I followed the tutorial of Fabien Potiencier, about how to create your own Framework on top of the Symfony Components. Now i need a way. And I want to inject the Dependency Container to all my Controllers, without defining every single Controller as a Service.

In the orginal Symfony2 Framework all Controllers extends the Controller Class located in Symfony\Bundle\FrameworkBundle\Controller\Controller.php:

namespace Symfony\Bundle\FrameworkBundle\Controller;

class Controller extends ContainerAware
{
   // ...
}

The Controller Class extends the ControllerAware Class, so you can do something like this in your Controller:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
   public function someAction()
   {
      $this->container->get('dependencie_xyz);
   }
}

So my question is: How can I accomplish the same in my Framework?

like image 322
c4pone Avatar asked Mar 23 '26 18:03

c4pone


1 Answers

It took me a while, but i finally figured out how the Symfony2 Framework does it. In the SymfonyFrameworkBundle is a custom ControllerResolver, which call the setContainer Method on the resolved controller. The controller has to be a instance of the ContainerAwareInterface.

Simplified version:

class ContainerAwareControllerResolver extends ControllerResolver
{
    private $container;

    public __construct(ContainerInterface $container)
    {
        $this->container = $container;
            parent::__construct();
    }

    public function getController(Request $request)
    {
        $controller = parent::getController($request);
        if($controller instanceof ContainerAware ){
            $controller->setContainer($this->container);
        }
    }
}

Source:

https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php

like image 73
c4pone Avatar answered Mar 25 '26 16:03

c4pone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!