Symfony2 - How to add a global parameter to routing for every request or generated URL similar to _locale?

旧巷老猫 提交于 2019-12-05 10:27:53

Your problem isn't very clear, but you might want to check your listener priority is set so that it runs before the router listener.


EDIT:

Assuming you're not trying to set the value of _applicationid in your twig view using path() – e.g. {{ path('path_name', {'_applicationid': 2}) }} – which will work, and may be the better option – you should still be able to set it using a listener.

After examining Symfony's own LocaleListener, I was able to set the value of _applicationid to 2 with the statement $this->router->getContext()->setParameter('_applicationid', 2);. The priority of the subscriber doesn't seem to make any difference, but setting the value in the view takes precedence over the listener.

Framework routing:

# app/config/routing.yml
acme_test:
    resource: "@AcmeTestBundle/Resources/config/routing.yml"
    prefix:   /{_applicationid}
    defaults:
        _applicationid: 0
    requirements:
        _applicationid: 0|1|2|3|4

Bundle Routing:

# src/Acme/TestBundle/Resources/config/routing.yml
acme_test_home:
    path:     /
    defaults: { _controller: AcmeTestBundle:Default:index }

Service definition:

# src/Acme/TestBundle/Resources/config/services.yml
services:
    acme_test.listener.app_id_listener:
        class: Acme\TestBundle\EventListener\AppIdListener
        arguments:
            - "@router"
        tags:
            - { name: kernel.event_subscriber }  

Subscriber:

# src/Acme/TestBundle/EventListener/AppIdListener.php
namespace Acme\TestBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AppIdListener implements EventSubscriberInterface
{
    private $router;

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

    public function onKernelRequest(GetResponseEvent $event)
    {
        $this->router->getContext()->setParameter('_applicationid', 2);
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
        );
    }
}

The easiest way to achieve this is by overriding symfony's default router service.

You can find an example how to override the default router in the JMSI18nRoutingBundle.

Take a look at I18nRouter and SetRouterPass


The alternative would be adding a custom route-loader that adds all the prefixed routes.

You can find examples for this in the documentation chapter How to Create a Custom Route Loader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!