Symfony 4.4 Event Listener Error (MongoDB)

I’m trying to create a listener to when a new Rating is created. I followed all the documentation but I keep getting the same error:
Argument 1 passed to "SymfonyComponentEventDispatcherEventDispatcherInterface::dispatch()" must be an instance of "SymfonyComponentEventDispatcherEvent", "AppEventAverageRatingEvent" given.

I’m trying to use SymfonyComponentEventDispatcherEvent in the event but it keeps saying that it is deprecated and according to documents to use SymfonyContractsEventDispatcherEvent instead.

I register my event in the services and the following is my event, eventlistener and class

Class Rating

class RatingApiController extends AbstractController
{
        
    /**
     * @Route("api/rating/create", name="CreateRating",  methods={"POST"})
     * @param DocumentManager $dm
     * @param Request $request
     * @param EventDispatcher $eventDispatcher
     * @return RedirectResponse|Response
     * @throws MongoDBException
     * 
     */
    public function addRating(Request $request, EventDispatcherInterface $eventDispatcher)
    {
        $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();
           
           $averageRatingEvent = new AverageRatingEvent($rating);
           $eventDispatcher->dispatch( AverageRatingEvent::NAME, $averageRatingEvent);
            

           $status = 200;
           $response = ["status" => $status, "success" => true, "data" => $rating->getId()];
           // return $this->redirectToRoute('rating_list'); 
       }



}

Event

<?php
namespace AppEvent;

use AppDocumentRating;
use SymfonyContractsEventDispatcherEvent;

class AverageRatingEvent extends Event
{
    /**
     * @var Rating $rating
     */
    protected $rating;

    public const NAME = "average.rating";
    
    public function __construct(Rating $rating)
    {
        $this->rating = $rating;        
    }

    public function getRating()
    {
        return $this->rating;
    }
    
}

Listener

<?php

namespace AppEvent;

use AppDocumentRating;
use DoctrineODMMongoDBEventLifecycleEventArgs;

class AverageRatingListener
{
    public function postPersist(LifecycleEventArgs $args)
    {
        $document = $args->getObject();
        if(!$document instanceof Rating)
        return;
    }


    public function RatingCreated()
    {
        dump("Hello a rating was just added");
    }
}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

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