[英]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.