繁体   English   中英

在路由中设置url参数(Symfony 2.6)

[英]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-producttype参数,该参数应该链接到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.

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