Accessing the service inside the event subscriber

I have an event subscriber with Doctrine events. Inside this, I am trying to call the service that I have registered. I've already called this from the controller and it works there, but when I try to call it in my subscriber, I get the error:

Attempted to call method "get" on class "Path\To\My\Class".
Did you mean to call "getSubscribedEvents"?

      

The code looks like this:

$embedcode_service = $this->get('myproject.mynamespace.myfield.update');
$embedcode_service->refreshMyField($document);

      

Why can't I access my service inside this event? How can I access it?

+3


source to share


1 answer


Kerad already answered that I'm just going to clarify:

Add your service to your subscriber:

services:
    ...
    my.subscriber:
            class: Acme\SearchBundle\EventListener\SearchIndexerSubscriber
            # Service you want to inject
            arguments: [ @service_i_want_to_inject.custom ]
            tags:
                - { name: doctrine.event_subscriber, connection: default }
   ...

      

In the php code for your subscriber, assign the injected service to a class variable so that you can access it later:

...
class SearchIndexerSubscriber implements EventSubscriber {

private $myservice;

public function __construct($myservice) {
    $this->myservice = $myservice;
}
...

      



Accessing service methods through a class variable from any method in the subscriber:

$this->myservice->refreshMyField($document);

      

Listeners / Subscribers in Symfony2

Services in Symfony2

Happy New Year.

+4


source







All Articles