【问题标题】:Forming URLs in Yii2在 Yii2 中形成 URL
【发布时间】:2015-04-28 18:06:20
【问题描述】:

我在 Yii2 配置文件中设置了 enablePrettyUrltrueshowScriptNamefalse。我的默认控制器名为public

我也有这两条规则:

[
    'pattern' => '<category_id:\w{6}>/<product_id:\w{6}>/<slug:.*?$>/',
    'route' => 'public/product',
    'defaults' => [
        'seo_url' => ''
    ]
],
[
    'pattern' => 'public/<category_id:\d{6}>/<product_id:\d{6}>/<slug:.*?$>/',
    'route' => 'public/product',
    'defaults' => [
        'seo_url' => ''
    ]
]

允许我使用以下 URL 访问我的页面中的产品:

http://example.com/123456/987654/this-is-a-prodduct-example-url

现在,我希望这样:

Url::to(["/product", "category_id" => 123456, "product_id" => 98765, "slug" => "this-is-a-product-example-url"]);

形成任何一个:

/123456/987654/this-is-a-product-example-url
/product/123456/987654/this-is-a-product-example-url
/public/product/123456/987654/this-is-a-product-example-url

但我却得到了这个:

/product/?category_id=123456&product_id=987654&slug=this-is-a-product-example-url

为什么会这样,我该如何解决?

【问题讨论】:

  • 也许是['public/product', ...] 而不是['product', ...]

标签: php yii2


【解决方案1】:
  1. 在模式中,您的意思很可能是因为您使用的是数字,而不是字母。
  2. 对于单个控制器操作参数,您可以有多个规则,但在形成 URL 时只会使用第一个。
  3. 您正在使用 /product,但它应该始终是内部路由,即控制器/动作或模块/控制器/动作。

【讨论】:

  • 对于 1,这实际上是正确的,因为 id 也可以包含字母。对于 2 和 3,是的,我希望匹配和使用第一条规则,但事实并非如此。我也试过/public/product(开头有斜杠和不带斜线),结果是一样的。
  • 空的 seo_url 有什么用?
  • 如果我在形成 URL 时不传递它,我希望它默认为 '' 而不是 null
  • 您可以在操作中指定默认值,即公共函数actionSomething($seo_url = '')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-24
  • 2016-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多