【发布时间】:2016-10-13 01:53:13
【问题描述】:
我是 Yii2 的新手,所以我有 Brands 表,其中包含它们的类型 ('brand', 'author', 'company') 和它们的 slug 名称,所以我需要像 www.site.com/{brand_type}/{brand_slug} 这样没有控制器名称的 URL,那么该怎么做?
【问题讨论】:
我是 Yii2 的新手,所以我有 Brands 表,其中包含它们的类型 ('brand', 'author', 'company') 和它们的 slug 名称,所以我需要像 www.site.com/{brand_type}/{brand_slug} 这样没有控制器名称的 URL,那么该怎么做?
【问题讨论】:
这通常称为漂亮的 URL。要在 Yii2 中实现这一点,请将其放在您的应用程序配置文件中 'components' 键下
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// ...
'<type:\w+>/slug:\w+>' => 'yourcontroller/youraction',
// ...
],
],
结果是,当您以您指定的格式传递 URL 时,您的控制器将 $type 和 $slug 作为您可以在控制器中使用的参数,预计采用以下形式:
class YourcontrollerController extends YourBaseController
{
...
public function actionYouraction($type, $slug)
{
// Do whatever you want with these variables
}
...
}
请注意,您将需要您的网络服务器来配置执行应用程序的index.php,即使它不在 URL 中。例如,对于 Apache,可以使用 .httaccess (More details here) :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
The Definitive Guide to Yii 2.0 有一个关于这个主题的精彩部分
【讨论】:
$slug 变量和 $type 变量将可供控制器执行任何您想做的事情