schmittjoh / JMSDiExtraBundle

Provides Advanced Dependency Injection Features for Symfony2
http://jmsyst.com/bundles/JMSDiExtraBundle
330 stars 130 forks source link

Lack document of define container as a service with JMSDiExtraBundle and @Route #110

Open bronze1man opened 11 years ago

bronze1man commented 11 years ago

Define container as a service with JMSDiExtraBundle

/**
@DI\Service("test_controller",parent="tbf.container_aware")
@Route ("/test", service="test_controller") 
**/
TestController extends Controller{
...
}

Here tbf.container_aware is an abstract service to inject container to container_aware.

        $container->setDefinition('tbf.container_aware',
            new Definition())
            ->setAbstract(true)
            ->addMethodCall('setContainer',array(
                new Reference('service_container')));

benefit: 1.test_controller is a service ,I can get it from container,and use it. 2.test_controller is a controller , I can add some route on it, and response some http request. 3.test_controller is a service ,I can use JMSAopBundle.

a better way to define container as a service ?

stof commented 11 years ago

Well, the main benefit of defining a controller as a service is using dependency injection in the controller class. If you inject the whole container in it, you are loosing this benefit (as you are injecting the whole world as a dependency)

bronze1man commented 11 years ago

I think using dependency injection in the controller class is just one benefit. I can reuse the code in controller thought container. Or I can injection this service into another service. Or I can add a tag on it,to listen on some stuff. Or I can create a route base on controller service name.

I even think controller should always be a service.

BTW: Injecting the whole world as a dependency is better then use the whole world with global function or variable.