如何解决Symfony 4.4事件分派器
我遇到以下错误:
找不到服务“ 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);
}
}
解决方法
事件分发程序不包含在AbstractController容器中。
检查symfony文档: 在这里,您可以找到如何使用事件分配器的示例: https://symfony.com/doc/4.4/components/event_dispatcher.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。