php - 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
推荐阅读
- python - 绘制风向
- python - 初学者:Python 3.66。赢7。如何忽略此代码中的子文件夹?
- qt - Qt - 如何从同一文件中的另一个函数获取变量值
- javascript - Axios 使用 vuejs cli 获取 php 文件不起作用
- r - 在 R 中使用 dpois 函数构建预测模型
- angular - 获取角度页面中的绑定总数
- java - 春天:PESSIMISTIC_READ/WRITE 不工作
- c - 奇怪的 Clang 行为。简单的片段给出了错误的结果
- python-3.x - 在轴值中添加辅助描述,情节
- laravel - Laravel 是否可以像 cakephp 的命令 cake bake all 那样从现有表中生成所有 mvc 骨架