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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With