Symfony 4.4 Event Dispatcher

**I’m getting the following error: **
Service "event_dispatcher" not found: even though it exists in the app’s container, the container inside "AppControllerRatingApiController" is a smaller service locator that only knows about the "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead.

I’m used to using

 $this->get('event_dispatcher')->dispatch( AverageRatingEvent::NAME, new AverageRatingEvent($rating));

for dispatching an event but ‘event_dipatcher’ is giving an error I can’t seem to find the source.

This is part of my controller:

<?php

namespace AppController;

use SymfonyComponentRoutingAnnotationRoute;
use DoctrineODMMongoDBMongoDBException;
use SymfonyComponentHttpFoundationRedirectResponse;
use AppDocumentRating;
use AppEventAverageRatingEvent;
use AppFormTypeRatingType;
use AppHelpersFormErrorsSerializer;
use DoctrineODMMongoDBDocumentManager;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentEventDispatcherEventDispatcherInterface;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentEventDispatcherEvent;

class RatingApiController extends AbstractController
{
    private $documentManager;
    public function __construct(DocumentManager $documentManager)
    {
        $this->documentManager = $documentManager;
    }

class RatingApiController extends AbstractController
{
    private $documentManager;
    public function __construct(DocumentManager $documentManager)
    {
        $this->documentManager = $documentManager;
    }

        
    /**
     * @Route("api/rating/create", name="CreateRating",  methods={"POST"})
     * @param DocumentManager $dm
     * @param Request $request
     * @return RedirectResponse|Response
     * @throws MongoDBException
     */
    public function addRating(Request $request, EventDispatcherInterface $dispatcher)
    {
        $response = [];

        $form = $this->
        createForm(RatingType::class, new Rating() ,array('csrf_protection' => false));  
        

        $request = json_decode($request->getContent(), true);
        
        $form->submit($request);

        if($form->isSubmitted() && $form->isValid())
        {
        
           $rating = $form->getData();

           $this->documentManager->persist($rating);
           $this->documentManager->flush();
           
        //    $event = new AverageRatingEvent($rating);
           $this->get('event_dispatcher')->dispatch( AverageRatingEvent::NAME, new AverageRatingEvent($rating));
        //    $dispatcher->dispatch(AverageRatingEvent::NAME, $event);

}
}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *