[英]Symfony2 - 2 routes to same bundle (optional parameter)
我需要使用2个不同的URL访问我的网站,例如:
/ blog =>主页
/ blog / article / 1 =>文章页面(等)
/ abcde / blog =>主页
/ abcde / blog / article / 1 =>文章页面(等)
当“abcde”在我的URL中时,我需要运行相同的控制器/操作,但能够获得此“abcde”值(此参数将导致一些更改)。
我发现了许多类似的问题,但从来没有找到我想要的东西:
初始app / config / routing.yml
mywebsite_blog: resource: "@MywebsiteBlogBundle/Resources/config/routing.yml" prefix: /blog/
如果我只是添加第二条路线,因为resource
是相同的,它会覆盖第一条路线。
我试图在初始路线上添加一个可选参数:
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上创建自定义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,以防这里知道很重要) ,检查是否为空等等。但显然它只适用于一个控制器/动作( Index:home
)。 我想改变它,以便它可以适用于我的整个MywebsiteBlogBundle。
在我的自定义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);
}
但:
它似乎不是很干净(但如果这是我现在发现它的唯一方法,我会试试)
我试着让我所有的路线都读到这个答案 ,一旦我尝试$collection = $router->getRouteCollection();
我有一个“检测到循环引用”错误,我无法修复。 我想知道这里发生了什么。 编辑: 我修好了。 不过,我认为这不是一个非常干净的解决方案。
我应该回到routing.yml还是可以使用自定义路由加载器做一些事情?
你应该在routing.yml
尝试这个:
mywebsite_blog:
resource: "@MywebsiteBlogBundle/Resources/config/routing.yml"
prefix: /{_label}blog/
defaults: {_label: mylabel/}
requirements:
_label: ([\w\d]+/)?
结果:
app/console router:match /mylabel/blog/ # OK
app/console router:match /blog/ # OK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.