php – Symfony2 – 同一捆绑的2条路由(可选参数)
我需要使用2个不同的URL访问我的网站,例如:
当“abcde”在我的URL中时,我需要运行相同的控制器/操作,但能够获得此“abcde”值(此参数将导致一些更改). 我发现了许多类似的问题,但从来没有找到我想要的东西: >我不是在寻找语言/翻译路由包 >初始app / config / routing.yml mywebsite_blog: resource: "@MywebsiteBlogBundle/Resources/config/routing.yml" prefix: /blog/ >如果我只是添加第二条路线,因为资源是相同的,它会覆盖第一条路线. mywebsite_blog: resource: "@MywebsiteBlogBundle/Resources/config/routing.yml" prefix: /{_label}/blog/ defaults: {_label: mylabel} requirements: _label: .* 这样我就可以访问/ abcde / blog,// blog,但不能访问/ blog(404). 没有找到如何使用routing.yml解决我的问题(如果有可能我会很乐意学习如何并停在那里),我在Symfony doc上阅读了How to Create a custom Route Loader .我不确定我是否会朝着正确的方向努力,但我尝试了它并设法做了一些事情,但仍然不是我想要的. LabelLoader.php class LabelLoader extends Loader { private $loaded = false; public function load($resource,$type = null) { if (true === $this->loaded) { throw new RuntimeException('Do not add the "label" loader twice'); } $routes = new RouteCollection(); // Prepare a new route (this is were I tried to play with it) $path = '/{_label}/blog/'; $defaults = array( '_controller' => 'MywebsiteBlogBundle:Index:home',); $route = new Route($path,$defaults); // Add the new route to the route collection $routeName = 'labelRoute'; $routes->add($routeName,$route); $this->loaded = true; return $routes; } public function supports($resource,$type = null) { return 'label' === $type; } } 这样,/ blog和/ abcde / blog按照我想要的方式工作.我可以在我的_init()函数中访问_label变量(我正在使用listeners和InitializableControllerInterface,以防在这里知道很重要),检查是否为空等等. 在我的自定义Loader中,我想测试类似于: $routes = new RouteCollection(); // Hypotetical function returning all the routes I want to have twice. // Methods getPath() and getController() called below are hypotetical too. $mywebsiteBlogRoutes = getExisitingMywebsiteBlogBundleRoutes(); foreach($mywebsiteBlogRoutes as $blogRoute) { // Prepare a new route $path = '/{_label}/blog/'.$blogRoute->getPath(); $defaults = array( '_controller' => $blogRoute->getController(),); $route = new Route($path,$defaults); // Add the new route to the route collection $routeName = 'labelRoute'; $routes->add($routeName,$route); } 但: >它似乎不是很干净(但如果这是我现在发现它的唯一方法,我会试试) 我应该回到routing.yml还是可以使用自定义路由加载器做一些事情? 解决方法
你应该在routing.yml中尝试这个:
mywebsite_blog: resource: "@MywebsiteBlogBundle/Resources/config/routing.yml" prefix: /{_label}blog/ defaults: {_label: mylabel/} requirements: _label: ([wd]+/)? 结果: app/console router:match /mylabel/blog/ # OK app/console router:match /blog/ # OK (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |