Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get container instance in sonata Admin class?

I need to parse some configurations parameters from my config.yml such as enabled languages. But when i try to do that by using the normal symfony method: $this->container->get('my_params'); it fails because my admin class extends Sonata\AdminBundle\Admin\Admin class which does not extend the Symfony\Component\DependencyInjection\ContainerAware class.

Please, How to get the container inside the sonata Admin class ?

Now i'm resolving this problem by overriding the sonata Admin Class to make it extends the ContainerAware.

like image 870
skonsoft Avatar asked Sep 01 '12 00:09

skonsoft


2 Answers

probably already resolved, because its an old question, but just for reference, the container is already available in admin class using the configuration pool...

$this->getConfigurationPool()->getContainer();

Of course, it is better practice to inject services in the admin class, but, like in the controllers. why would someone, take the time to configure setter injection if already has the container available?

like image 137
Javier Neyra Avatar answered Oct 15 '22 19:10

Javier Neyra


Add in your Admin class

/** @var \Symfony\Component\DependencyInjection\ContainerInterface */
private $container;

public function setContainer (\Symfony\Component\DependencyInjection\ContainerInterface $container) {
    $this->container = $container;
}

And add calls in services configuration(configuration can be specified in YAML, XML or PHP):

YAML

calls:
    - [ setContainer, [ @service_container ] ]

XML

 <call method="setContainer">
     <argument type="service" id="service_container" />
 </call>

Now you can using the normal symfony method: $this->container->get()

For more information see Service Container documentation

like image 16
Максим Шатов Avatar answered Oct 15 '22 17:10

Максим Шатов