在每个页面调用一个路由

Call an route on each page

我有一个问题。我添加了一项新服务 PopupListener.php:

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\ContainerInterface;


class PopupListener
{
    protected $router;

    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    public function onKernelRequest()
    {
        $this->router->generate('app_popup_trigger');
    }
}

services.yml :

popup_listener:
    class: App\DesktopBundle\Listeners\PopupListener
    arguments: ["@router"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

routing.yml :

app_popup_trigger:
    path: /popup/trigger
    defaults: { _controller: AppDesktopBundle:Popup:triggerPopup }

triggerPopupAction :

class PopupController extends Controller{
    public function triggerPopupAction(){
        return $this->render('AppDesktopBundle:Popup:index.html.twig', array());
    }
}

我希望在每条路线上调用添加的新路线:app_popup_trigger。我做了一些类似的想法但没有工作。路由没有被调用。你能帮帮我吗?

要在每个请求开始时调用特定路由,您只需在 PopupListener 中扩展代码:

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class PopupListener
{
    protected $router;

    protected $httpKernel;

    public function __construct(Router $router, HttpKernelInterface $httpKernel)
    {
        $this->router = $router;
        $this->httpKernel = $httpKernel;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return;
        }

        $subRequest = Request::create($this->router->generate('app_popup_trigger'));
        $response = $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
        // do something with the $response here
    }
}

Symfony 将只为这个子请求启动一个新的请求-响应周期,并将 return 这个周期的 $response。然后你必须决定你要用那个响应做什么。

然后将附加服务添加到您的服务配置中:

popup_listener:
    class: App\DesktopBundle\Listeners\PopupListener
    arguments: ["@router", "@http_kernel"]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

您可以在此处获得有关 symfony 子请求的更多信息:The HttpKernel Component - Sub Request。我链接了 Symfony 2.3 的文档。但请记住,Symfony 2.3 不再维护,您应该考虑升级到 3.x.

基本上使用 FOSJsRoutingBundle 并使用 javascript 触发您的路线。这将比弹出窗口的侦听器更容易。