[英]Set url parameter in route (Symfony 2.6)
因此,假設我在DisplayController.php
得到了showAction()
:
/**
* @param $type
* @param $slug
* @return \Symfony\Component\HttpFoundation\Response
*/
public function showAction($type, $slug)
{
...
}
通常,以下路線鏈接到此操作:
my_bundle_display_show:
pattern: /display/{type}/{slug}
defaults: { _controller: MyFunnyBundle:Display:show }
因此,當我請求my-website.com/display/product/A
,一切都會按預期進行。
但是,現在我需要實現一個快速鏈接,該鏈接要求我跳過看起來像my-website.com/specific-product
的type
參數,該參數應該鏈接到my-website.com/display/product/specific-product
。 我為此創建的路由如下所示:
my_bundle_display_show_specific_product:
pattern: /{slug}
defaults: { _controller: MyFunnyBundle:Display:show }
requirements:
slug: "specific-product"
defaults:
type: "product"
特定的錯誤消息是Controller "MyBundle\\Controller\\DisplayController::showAction()" requires that you provide a value for the "$type" argument (because there is no default value or because there is a non optional argument after this one).
但是,這不起作用,因為我需要添加$type
才能使其正常工作。 我可以創建一個新的showSpecificProductAction
,但是我不想這樣做,因為這兩個函數基本上都相同。 所以我想知道是否可以在路由內“設置”變量,這樣我基本上只能使$slug
成為實際變量,而無需編輯showAction()
本身?
在Controller動作中,將功能更改為public function showAction($type='product', $slug)
不要搜索更簡單/更短的解決方案。 正確做事,以后不會有任何問題。
首先,定義您的路由邏輯/目標。 如果您想使用短網址將您重定向到整個頁面,則可以這樣做。 您可以立即在yaml中執行以下操作:
my_bundle_display_show_specific_product:
path: /{slug}/
defaults:
_controller: FrameworkBundle:Redirect:redirect
route: my_bundle_display_show
permanent: true
type: "some default value"
如果您不知道默認類型值,只需在controller中創建新操作,找到該值並從提供該值並使用正確的HTTP代碼的controller重定向。 這樣的重定向對SEO也是有好處的:
public function actionOne($slug) {
$type = ... // find out the type
return $this->redirectToRoute('actionTwo', ['type' => $type, 'slug' => $slug], 301);
}
public function actionTwo($type, $slug) {
// do some stuff...
}
如果您確實需要兩個網址都可以工作,則只需創建2個路由配置和2個操作即可。 但是,由於它們具有通用邏輯,因此請在控制器中創建一個私有方法,這將為兩個邏輯都做。 這就是OOP的全部意義:
public function actionOne($slug) {
$type = ... // find out the type
return $this->renderProduct($type, $slug);
}
public function actionTwo($type, $slug) {
return $this->renderProduct($type, $slug);
}
private function renderProduct($type, $slug) {
return $this->render('view', [...]);
}
首先考慮邏輯,然后考慮單獨的邏輯部分(使用路由/控制器/動作)。 這就是全部。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.