在URL规则中使用正则表达式
Yii URL路由器的一个隐藏特性是,你可以使用正则表达式来处理地址。
准备
- 按照官方指南http://www.yiiframework.com/doc-2.0/guide-start-installation.html的描述,使用Composer包管理器创建一个新的应用。
- 在你的
@app/controllers文件夹中,使用如下代码创建PostController.php:
<?phpnamespace app\controllers;use yii\helpers\Html;use yii\web\Controller;class PostController extends Controller{public function actionView($alias){return $this->renderContent(Html::tag('h2', 'Showing post with alias ' . Html::encode($alias)));}public function actionIndex($type = 'posts', $order = 'DESC'){return $this->renderContent(Html::tag('h2', 'Showing ' . Html::encode($type) . ' ordered ' . Html::encode($order)));}public function actionHello($name){return $this->renderContent(Html::tag('h2', 'Hello, ' . Html::encode($name) . '!'));}}
这是我们的应用控制器,我们将会使用自定义URL来方法它。
- 配置你的应用服务器,来使用干净的URL。如果你在使用带有
mod_rewrite的Apache,并打开了AllowOverride,那么你就可以添加如下内容到@web文件夹下的.htaccess文件中:
Options +FollowSymLinksIndexIgnore */*RewriteEngine on# if a directory or a file exists, use it directlyRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-d# otherwise forward it to index.phpRewriteRule . index.php
如何做…
我们希望我们的PostController动作根据一些指定的规则接受参数,并将其它所有不匹配的参数给以404 not found的HTTP响应。此外,post/index应该有一个alias URL archive。
添加如下urlManager组件配置到@app/config/web.php:
'components' => [// ..'urlManager' => ['enablePrettyUrl' => true,'rules' => ['post/<alias:[-a-z]+>' => 'post/view','<type:(archive|posts)>' => 'post/index','<type:(archive|posts)>/<order:(DESC|ASC)>' => 'post/index','sayhello/<name>' => 'post/hello',]],// ..],
如下URL将会成功:
http://yii-book.app/post/testhttp://yii-book.app/postshttp://yii-book.app/archivehttp://yii-book.app/posts/ASChttp://yii-book.app/sayhello
如下URL将会失败:
http://yii-book.app/archive/testhttp://yii-book.app/post/another_post
下面的截图展示了http://yii-book.app/post/test运行是成功的:

下面的截图展示了http://yii-book.app/archive也可以运行成功:

下面的截图展示http://yii-book.app/archive/test没有运行成功,并有一个报错:

工作原理…
你可以在参数定义和规则的其它部分使用正则表达式。下面我们一条一条的看这些规则:
'post/<alias:[-a-z]+>' => 'post/view',
alias参数应该包含一个或多个英文单词或者一个-。其它符号不被允许。
'(posts|archive)' => 'post/index','(posts|archive)/<order:(DESC|ASC)>' => 'post/index',
posts和archive都会指向post/index。order参数只接受两个值——DESC和ASC:
'sayhello/<name>' => 'post/hello',
你应该指定名称部分,但是没有对可以使用的单词做限制。注意到不管使用的规则是什么,开发者不应该假设输入的数据是安全的。

更多…
欲了解更多关于正则表达式的信息,你可以使用如下资源:
- http://www.php.net/manual/en/reference.pcre.pattern.syntax.php
- http://regex.info/提供的掌握正则表达式,Jeffrey Friedl
参考
- 配置URL规则小节
