在URL规则中使用正则表达式

Yii URL路由器的一个隐藏特性是,你可以使用正则表达式来处理地址。

准备

  1. 按照官方指南http://www.yiiframework.com/doc-2.0/guide-start-installation.html的描述,使用Composer包管理器创建一个新的应用。
  2. 在你的@app/controllers文件夹中,使用如下代码创建PostController.php
  1. <?php
  2. namespace app\controllers;
  3. use yii\helpers\Html;
  4. use yii\web\Controller;
  5. class PostController extends Controller
  6. {
  7. public function actionView($alias)
  8. {
  9. return $this->renderContent(Html::tag('h2', 'Showing post with alias ' . Html::encode($alias)
  10. ));
  11. }
  12. public function actionIndex($type = 'posts', $order = 'DESC')
  13. {
  14. return $this->renderContent(Html::tag('h2', 'Showing ' . Html::encode($type) . ' ordered ' . Html::encode($order)));
  15. }
  16. public function actionHello($name)
  17. {
  18. return $this->renderContent(Html::tag('h2', 'Hello, ' . Html::encode($name) . '!'));
  19. }
  20. }

这是我们的应用控制器,我们将会使用自定义URL来方法它。

  1. 配置你的应用服务器,来使用干净的URL。如果你在使用带有mod_rewrite的Apache,并打开了AllowOverride,那么你就可以添加如下内容到@web文件夹下的.htaccess文件中:
  1. Options +FollowSymLinks
  2. IndexIgnore */*
  3. RewriteEngine on
  4. # if a directory or a file exists, use it directly
  5. RewriteCond %{REQUEST_FILENAME} !-f
  6. RewriteCond %{REQUEST_FILENAME} !-d
  7. # otherwise forward it to index.php
  8. RewriteRule . index.php

如何做…

我们希望我们的PostController动作根据一些指定的规则接受参数,并将其它所有不匹配的参数给以404 not found的HTTP响应。此外,post/index应该有一个alias URL archive。

添加如下urlManager组件配置到@app/config/web.php

  1. 'components' => [
  2. // ..
  3. 'urlManager' => [
  4. 'enablePrettyUrl' => true,
  5. 'rules' => [
  6. 'post/<alias:[-a-z]+>' => 'post/view',
  7. '<type:(archive|posts)>' => 'post/index',
  8. '<type:(archive|posts)>/<order:(DESC|ASC)>' => 'post/index',
  9. 'sayhello/<name>' => 'post/hello',
  10. ]
  11. ],
  12. // ..
  13. ],

如下URL将会成功:

  • http://yii-book.app/post/test
  • http://yii-book.app/posts
  • http://yii-book.app/archive
  • http://yii-book.app/posts/ASC
  • http://yii-book.app/sayhello

如下URL将会失败:

  • http://yii-book.app/archive/test
  • http://yii-book.app/post/another_post

下面的截图展示了http://yii-book.app/post/test运行是成功的:

在URL规则中使用正则表达式 - 图1

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

在URL规则中使用正则表达式 - 图2

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

在URL规则中使用正则表达式 - 图3

工作原理…

你可以在参数定义和规则的其它部分使用正则表达式。下面我们一条一条的看这些规则:

  1. 'post/<alias:[-a-z]+>' => 'post/view',

alias参数应该包含一个或多个英文单词或者一个-。其它符号不被允许。

  1. '(posts|archive)' => 'post/index',
  2. '(posts|archive)/<order:(DESC|ASC)>' => 'post/index',

postsarchive都会指向post/indexorder参数只接受两个值——DESCASC

  1. 'sayhello/<name>' => 'post/hello',

你应该指定名称部分,但是没有对可以使用的单词做限制。注意到不管使用的规则是什么,开发者不应该假设输入的数据是安全的。

在URL规则中使用正则表达式 - 图4

更多…

欲了解更多关于正则表达式的信息,你可以使用如下资源:

参考

  • 配置URL规则小节