Inject service into controller in Symfony 2.8?
I’m really struggling to try to inject a service into a controller, I found some post and this is what I have tried:
I have a service called FormatService
services: formats_service: class: FormatsBundle\Services\FormatService
I want it to be injected into FormatsController
so I tried Defining Controllers as Services, then changed my entire routing as the docs states
app.formats_controller: class: ABundle\Controller\FormatsController arguments: ["@formats_service"]
Doing this gives me an Error: Call to a member function has() on null
error when I try to access to any endpoint from my control
Then I tried to gather it from the container doing something like this
public function __construct () { $this->formatService = $this->container->get('formats_service'); }
This gives me an error, $this->container
seems to be null.
I did a research and found this post INJECT the container to my controller but the solution is the same thing I couldn’t accomplish from the 1st point, I cant inject services since to do so I need to define my controller as a service but doing so gives me Error: Call to a member function has() on null
whenever I try to access to any endpoint from my controller
Is there any way to inject a service into a controller without doing an entire mess in Symfony 2.8?
When you use the controller you don’t need to declare it as a service because the controller have the container you can use php app/console debug:container to see if your service is in your container and you can use it directy into your actions
public function newAction()
{
// the container will instantiate a new FormatService() $myService = $this->container->get('formats_service');
}
you can see more here https://symfony.com/doc/2.8/service_container.html
When defining a controller as a service you have to inject the services directly without accessing the container. You can have a mixed approach when your controller extends Symfony’s base controller, but it is usually discouraged.
It should work if you modify your controller’s constructor:
public function __construct(FormatsBundle\Services\FormatService $formatService) { $this->formatService = $formatService; }
edit: If you want to use the container in your controller you should either extend Symfony\Bundle\FrameworkBundle\Controller\Controller
or add use Symfony\Component\DependencyInjection\ContainerAwareTrait
, but again both is discouraged when using controllers as a service, because then you could just as well write a regular controller.