简体   繁体   English

Symfony2中的动态路由前缀

[英]Dynamic route prefix in Symfony2

I am creating a SaaS with symfony2 providing private websites. 我正在使用提供私人网站的symfony2创建一个SaaS。 What I am trying to do is to let people access the website this way : 我想做的是让人们以这种方式访问​​该网站:

http://www.mydomain.com/w/ {website_name} http://www.mydomain.com/w/ {website_name}

Here is the routing configuration i am using : 这是我正在使用的路由配置:

websites:
    resource: "@MyBundle/Resources/config/routing.yml"
    prefix:   /w/{website_name}

The problem is that when I try to access, for exemple, http://www.mydomain.com/w/chucknorris I am getting the error : 问题是,当我尝试访问例如http://www.mydomain.com/w/chucknorris时,出现错误:

An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("website_name") to generate a URL for route "websites_homepage".") in "MyBundle:Publication:publicationsList.html.twig". 在呈现模板时,“ MyBundle:Publication:publicationsList.html.twig”中引发了一个异常(“缺少某些必需参数(“ website_name”)以生成路线“ websites_homepage”的URL。”

What I understood is that my route configuration is working well but when I am calling the router to generates url in the website it isn't aware of the "context" {website_name} url parameter. 据我了解 ,我的路由配置运行良好,但是当我调用路由器在网站中生成url时,却不知道“ context” {website_name} url参数。

One solution I've imagined is to find a way to automatically and seemlessly inject this parameter when it's set in the context. 我想过的一个解决方案是找到一种在上下文中设置此参数时自动将其参数注入的方法。

Until now all I've been able to do is to create a service to get this parameter this way : 到目前为止,我所能做的就是创建一个服务来以这种方式获取此参数:

public function __construct(Registry $doctrine, ContainerInterface $container) {

        $website_name = $container->get('request')->get("website_name");

        if (!empty($website_name)) {

            $repository = $doctrine->getManager()->getRepository('MyBundle:website');

            $website = $repository->findOneByDomain($website_name);
            if ($website) {
                $this->website = $website;
            } else {
                throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
            }
        } else {
            $this->isPortal = true;
        }
}

My question is : How do I inject that argument to all url generated to avoid getting the error of parameter missing and without having to specify it manualy everytime I call the router in controllers or twig ? 我的问题是:如何将这个参数注入生成的所有url中,以免丢失参数错误,而不必每次在控制器或树枝中调用路由器时都必须手动指定它? (I guess it's something about request event but i have no clue on how to do it and especialy how to do it according to symfony2 good usages) (我想这与请求事件有关,但是我不知道如何做到这一点,尤其是根据symfony2的良好用法如何做到这一点)

UPDATE Here is the listener i created base on locallistener provided by symfony: 更新这是我根据symfony提供的locallistener创建的侦听器:

    <?php    
class WebsiteNameRouteEventListener implements EventSubscriberInterface {    
        private $router;    
        public function __construct(RequestContextAwareInterface $router = null) {
            $this->router = $router;
        }
        public function onKernelResponse(FilterResponseEvent $event) {            
            $request = $event->getRequest();
            $this->setWebsiteName($request);
        }    
        public function onKernelRequest(GetResponseEvent $event) {
            $request = $event->getRequest();    
            $this->setWebsiteName($request);           
        }    
        public static function getSubscribedEvents() {
            return array(
                // must be registered after the Router to have access to the _locale
                KernelEvents::REQUEST => array(array('onKernelRequest', 16)),
                KernelEvents::RESPONSE => 'onKernelResponse',
            );
        }    
        private function setWebsiteName(Request $request) {           
            if (null !== $this->router) {
                echo "NEW CODE IN ACTION";die();
                $this->router->getContext()->setParameter('website_name', $request->attributes->get("website_name"));
            }
        }    
    }

But i am still getting this error : 但是我仍然收到此错误:

An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("website_name") to generate a URL for route "homepage".") in "MyBundle:Publication:publicationsList.html.twig". 在呈现模板期间,“ MyBundle:Publication:publicationsList.html.twig”中引发了一个异常(“缺少某些强制性参数(“ website_name”)以生成路线“ home”的URL。“)。 500 Internal Server Error - Twig_Error_Runtime 1 linked Exception: 500内部服务器错误-Twig_Error_Runtime 1链接的异常:

 MissingMandatoryParametersException » 

Without my echo "...."; 没有我的回声“ ....”; die() being executed so i guess twig is not firing the event i am listening on when it execute the path(routename) code. die()正在执行,因此我猜它在执行path(routename)代码时不会触发我正在监听的事件。

Any idea ? 任何想法 ?

You could use the router context. 您可以使用路由器上下文。

$this->router->getContext()->setParameter('website_name', $website_name);

See this file: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/EventListener/LocaleListener.php 看到这个文件: https : //github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/EventListener/LocaleListener.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM