DVC
DVC

Reputation: 29

How to access the service container in order to use JMSSerializer?

According to the documentation:

The container is available in any traditional Symfony2 controller where you can access the services of the container via the get() shortcut method

So, I have managed to invoke and use JMSSerializer within a Controller by calling:

$serializer = $this->get('serializer');

However, how can I invoke the container in a custom class? The same command fails indicating Fatal Error for calling undefined method get().

Upvotes: 2

Views: 5212

Answers (1)

MDrollette
MDrollette

Reputation: 6927

This is exactly what dependency injection is for. Your "custom class" has a dependency on the "serializer" service. So, you should define your class as a service in the service container

app/config/config.yml

services:
    my_custom_class:
        class:        My\RandomBundle\CustomClass
        arguments:    [serializer]

My\RandomBundle\CustomClass

use JMS\SerializerBundle\Serializer\Serializer;

class CustomClass
{
    private serializer;

    public function __construct(Serializer $serializer)
    {
        $this->serializer = $serializer;
    }
}

Now you can get your custom class from the container wherever it's used and it will automatically have the serializer available to it.

$myServiceWithASerializer = $this->container->get('my_custom_class');

The docs describe this as well:
http://symfony.com/doc/current/book/service_container.html#creating-configuring-services-in-the-container

Upvotes: 6

Related Questions