1

我收到以下错误:

未找到服务“event_dispatcher”:即使它存在于应用程序的容器中,但“App\Controller\RatingApiController”内的容器是一个较小的服务定位器,只知道“form.factory”、“http_kernel”、“parameter_bag”、 “request_stack”、“router”、“security.authorization_checker”、“security.csrf.token_manager”、“security.token_storage”、“serializer”、“session”和“twig”服务。尝试改用依赖注入。

我习惯用

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

用于调度事件但“event_dipatcher”给出错误我似乎无法找到源。

这是我的控制器的一部分:

<?php

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ODM\MongoDB\MongoDBException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use App\Document\Rating;
use App\Event\AverageRatingEvent;
use App\Form\Type\RatingType;
use App\Helpers\FormErrorsSerializer;
use Doctrine\ODM\MongoDB\DocumentManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\Event;

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);

}
}
4

1 回答 1

1

事件调度程序不包含在 AbstractController 容器中。

检查 symfony 文档:在这里你可以找到一个如何使用事件调度器的例子: https ://symfony.com/doc/4.4/components/event_dispatcher.html

于 2020-10-20T12:27:26.110 回答