Sonata admin controller + dependency injection

Viewed 1136

I am struggling with sonata admin and dependency injection. I defined a Admin class and use a own controller extending CRUDController for it.

In this Controller i have to do a HTTP Request, so i want to inject a Zend HTTP Client instance.

news.controller:
    class: MyBundle\Controller\NewsController
    arguments: ['@zend.httpclient']

news.admin
    class: MyBundle\Admin\NewsAdmin
    ...
    arguments:
       - null
       - MyBundle\Entity\News
       - MyBundle:News

The arguments from the news controller are never injected .. i think it is cause the admin don't care about my self defined controller as a service.

So i think i have to replace the direct class name as the 3rd parameter of the admin service with the id from the controller container service i defined as "news.controller". Now it looks like

news.admin
    class: MyBundle\Admin\NewsAdmin
    ...
    arguments:
       - null
       - MyBundle\Entity\News
       - news.controller

Now i get

Call to a member function has() on null

I think, there must be some missing configuration ... whats wrong?

Has somebody an idea how to inject things to the custom CRUDController and use it with sonata admin? Or how can i do that in another way? I need the CRUDController cause i defined an api for several AJAX calls from custom templates ... so there is also a need to have an entitymanager which is defined in the CRUDController ...

I also read that defining Controllers as services are not the best way ... but whats the proper way to make for example http calls with external clients like the zend client if i really need them?

1 Answers

The has() error indicates that while your controller is now properly wired up as a service, the container has not been injected. This injection is usually done by the controller resolver after it creates a new controller class. However, this step is not performed when pulling the controller from the container.

The solution is to inject the container via your service definition:

news.controller:
    class: MyBundle\Controller\NewsController
    arguments: ['@zend.httpclient']
    calls:[['setContainer', ['@service_container']]]

Lots of brackets but oh well.

Related