Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a service inside an event subscriber

I have an event subscriber with Doctrine events. Inside that, I am trying to call a service I have registered. I've called it already from in a controller and it works there, but when I try to call it in my event subscriber I get an 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 subscriber? How can I get access to it?

like image 442
beth Avatar asked Jan 01 '15 01:01

beth


People also ask

What is event subscriber in business central?

An event subscriber is a method that listens for a specific event that is raised by an event publisher. The event subscriber includes code that defines the business logic to handle the event. When the published event is raised, the event subscriber is called and its code is run.

How to add an event in c#?

On top of the Properties window, click the Events icon. Double-click the event that you want to create, for example the Load event. Visual C# creates an empty event handler method and adds it to your code. Alternatively you can add the code manually in Code view.


1 Answers

Cerad already answered I'm just going to elaborate:

Inject your service in 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 to be able to access it later on:

...
class SearchIndexerSubscriber implements EventSubscriber {

private $myservice;

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

Access the service methods through the class variable from any method within the subscriber:

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

Listeners/subscribers in Symfony2

Services in Symfony2

Happy new year.

like image 154
acontell Avatar answered Sep 30 '22 15:09

acontell