Symfony 4:请求对象更改

时间:2018-04-01 16:19:27

标签: symfony events symfony4

我正在研究Symfony 4。

我有服务:

    App\EventListener\EbayExceptionListener:
    tags:
        - { name: kernel.event_listener, event: kernel.controller }
    arguments: [ "@doctrine.orm.entity_manager" , "@router" , "@session" ]

这是我的倾听者:

<?php

namespace App\EventListener;

use App\Entity\Ebay;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\Routing\Router;

class EbayExceptionListener
{
    private $repository;
    private $router;
    private $session;
    private $redirectName = 'home';

    public function __construct(EntityManager $entityManager, Router $router, Session $session)
    {
        $this->repository = $entityManager->getRepository(Ebay::class);
        $this->router = $router;
        $this->session = $session;
    }

    //Check if an eBay entity exist in the database, if not redirect to the form to create the eBay entity
    public function onKernelController(FilterControllerEvent $event)
    {
        $ebay = $this->repository->findOneBy(['name' => 'Ebay']);
        $request = $event->getRequest();
        $routeName = $request->get('_route');
        dump($routeName);
        if ($routeName != "home" AND $ebay == null) {
            $this->session->getFlashBag()->add('error', 'Please provide information for Ebay form');
            return new RedirectResponse($this->router->generate($this->redirectName));
        }
    }
}

我的控制器:

<?php

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class HomeController extends Controller
{
    /**
     * @Route("/", name="home")
     */
    public function index()
    {
        return $this->render('home/index.html.twig', [
            'controller_name' => 'HomeController',
        ]);
    }
}

我的监听器中的var $routeName有问题,实际上这个变量的值应该是当前路由的名称。但是当我使用dump($routeName)

我有2个结果:&#34; _wdt&#34;和&#34;家&#34;

enter image description here

我不知道为什么执行我的监听器时以及生成页面后$request参数不相同。 因为我没有页面呼叫&#34; _wdt&#34;它应该是&#34; home&#34;。 我做错了吗?

感谢您的帮助。

0 个答案:

没有答案