我得到以下错误:
服务"event_dispatcher";未找到:即使它存在于应用程序的容器中;App\Controller\RatingApiController";是一个较小的服务定位器,它只知道";form.factory"http_kernel"parameter_bag"requestrongtack"路由器"security.authorization_checker"security.csrf.token_manager"security.token_storage"串行器"会话";以及";树枝;服务。请尝试使用依赖项注入。
我习惯于使用
$this->get('event_dispatcher')->dispatch( AverageRatingEvent::NAME, new AverageRatingEvent($rating));
用于调度事件,但"event_dipatcher"给出了一个错误,我似乎找不到源。
这是我的控制器的一部分:
<?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);
}
}
查看symfony文档:在这里,您可以找到一个如何使用事件调度器的示例:https://symfony.com/doc/4.4/components/event_dispatcher.html