Controller as Service (symfony 2.3)

Today we experimented a little bit with... accessing a controller from another controller.

The case for accessing a function of one controller from another controller is tricky and special. In most of the cases the job can be done with static functions! By declaring a function as
public static function averyspecialfunction
does your job, and this function is callable the usual way AKA
myController::averyspecialfunction
In this case you must be aware that a static function is not "container aware", meaning that the function is not able to access things like Entity Manager. If you really need to have access to all this kind of information maybe the way to do so is the Controller as Service.

In order to declare a Controller as a Service you have to open you config.yml (or services.yml if you organize your services in a separate yml) and add the following:
services:
    mycontroller.controller:
        class: Vacilos\DemoBundle\Controller\myController
        calls:
            - [setContainer, ["@service_container"]]
(in case you have more services just place it under services section)

In most of the cases and after searching around I found the same declaration without the calls: section. In this case you are able to get the job done but your controller as service is NOT container aware and thus not able to access staff like "Entity Manger".

After declaring the service (remember to delete your cache after such changes) you are able to access the controller (from another controller) the following way:

$mc = $this->get('mycontroller.controller'); // read the service as declared
$result = $mc->mypreciousfunction($anyvariable); // call any function
voila!

Comments

Popular Posts