在每个页面上呼叫路由

时间:2017-09-05 09:56:01

标签: php symfony symfony-2.3

我有一个问题。我添加了一个新服务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。我做了一些这样的想法,但没有工作。该路线未被调用。你能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

基本上使用FOSJsRoutingBundle并使用javascript触发您的路线。弹出窗口比听众容易。

答案 1 :(得分:0)

要在每个请求开始时调用特定路由,您只需要在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将为此子请求启动一个新的请求 - 响应周期,并将返回此周期的$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。