yii2路由篇 --- urlManager 配置详解

本文详细解析了Yii2框架中urlManager的配置,包括enablePrettyUrl、enableStrictParsing、rules等参数,通过多个示例展示了如何进行URL正则匹配、controller与action匹配、默认参数设置、域名匹配、请求方式匹配以及更高级的路由配置。建议在启用pretty URL时捕获'yiiwebNotFoundHttpException'异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

‘urlManager’ 参数详解

[
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => false,
            'suffix' => '.html',
            'rules' => [
                // ...
            ],
        ],
    ],
]

  • enablePrettyUrl : false 隐藏入口文件index.php, ex: /index.php/post/100 ==>>/post/100
  • enableStrictParsing : true 启动url严格匹配模式,匹配规则 yii\web\UrlManager::rules
  • rules : url 规则,注意定义不匹配时的默认路径(apache) yii\web\UrlRule
  • suffix : url 添加后缀名

‘rules’ 参数详解

示例1 url 正则匹配

### 示例1 url 正则匹配

'rules' => [
         posts/<year:\d{4}>/<category>' => 'post/index',
        'posts' => 'post/index',
        'post/<id:\d+>' => 'post/view',
    ],

url示例1 解析

  • /index.php/posts : 匹配第二条规则,实际url post/index
  • /index.php/posts/2014/php :匹配第一条规则,实际url post/index 参数year=2014,category=php
  • /index.php/post/100 : 匹配第三条规则,实际url post/view id=100
  • /index.php/posts/php : 不匹配任何规则,当’enableStrictParsing’ => false, 触发异常 yii\web\NotFoundHttpException!

示例2 url controller action正则匹配(常用)

### 示例2 url controller action正则匹配(常用)

'rules' => [
    '<controller:(post|comment)>/<id:\d+>/<action:(create|update|delete)>' => '<controller>/<action>',
    '<controller:(post|comment)>/<id:\d+>' => '<controller>/view',
    '<controller:(post|comment)>' => '<controller>/index',
    ],

url示例2 解析

  • /index.php/comment/100/create:匹配第一条规则,实际url /comment/100/create 参数id=100
  • /index.php/comment/100 :匹配第二条规则,实际url /comment/view 参数id=100
  • /index.php/comments : 匹配第三条规则,实际url /comment/index

示例3 url 默认参数

### 示例3 url 默认参数
### 减少编写规则(允许数组参数)

'rules' => [
        '<controller:(post|comment)>' => '<controller>/index',
        [
            'pattern' => 'posts/<page:\d+>/<tag>',
            'route' => 'post/index',
            'defaults' => ['page' => 1, 'tag' => ''],
        ],
    ],

url示例3 解析

  • /index.php/posts:匹配第一条规则,实际url post/index 参数page=1 tag=’’

示例4 域名匹配

### 示例4 域名匹配

'rules' => [
    'http://<language:\w+>.example.com/posts' => 'post/index',
    'http://admin.example.com/login' => 'admin/user/login',
    'http://www.example.com/login' => 'site/login',
    ],

url示例4 解析

  • 这种配置我比较少用到

示例5 请求方式匹配

### 示例5 请求方式匹配

'rules' => [
    'PUT,POST post/<id:\d+>' => 'post/create',
    'DELETE post/<id:\d+>' => 'post/delete',
    'post/<id:\d+>' => 'post/view',
    ],

url示例5 解析

  • 第一条匹配匹配规则,只允许 post put请求方式,否则抛出异常

示例6 更高级路由配置

### 动态加载路由设置 bootstrap (module模块使用更多)

public function bootstrap($app)
{
    $app->getUrlManager()->addRules([
        // rule declarations here
    ], false);
}



###  自定义路由类

#配置
'rules' => [
       '<controller:(post|comment)>' => '<controller>/index',
        [
            'class' => 'app\components\CarUrlRule', 
        ],
    ],


#php实现

namespace app\components;

use yii\web\UrlRuleInterface;
use yii\base\Object;

class CarUrlRule extends Object implements UrlRuleInterface
{

    public function createUrl($manager, $route, $params)
    {
        if ($route === 'car/index') {
            if (isset($params['manufacturer'], $params['model'])) {
                return $params['manufacturer'] . '/' . $params['model'];
            } elseif (isset($params['manufacturer'])) {
                return $params['manufacturer'];
            }
        }
        return false;  // this rule does not apply
    }

    public function parseRequest($manager, $request)
    {
        $pathInfo = $request->getPathInfo();
        if (preg_match('%^(\w+)(/(\w+))?$%', $pathInfo, $matches)) {
            // check $matches[1] and $matches[3] to see
            // if they match a manufacturer and a model in the database
            // If so, set $params['manufacturer'] and/or $params['model']
            // and return ['car/index', $params]
        }
        return false;  // this rule does not apply
    }
}


url示例6

  • 动态加载路由设置,首先implement yii\base\BootstrapInterface,然后重写bootstrap(),最后添加rules
  • 自定义路由匹配类 必须继承接口 implements UrlRuleInterface

NOTE:

  • 当使用优化’enablePrettyUrl’ => true,规则使用yii\web\UrlManager::rules ,默认使用yii\web\UrlRule的子类or实例
  • rules 使用前提:配置’enableStrictParsing’ => false
  • 建议抓捕异常yii\web\NotFoundHttpException,或重写apche等模块识别不了url的默认处理
异常处理方法:    
##参数配置 
'errorHandler' => [
            'errorAction' => 'site/error',
        ],

[引用BKDUCK博客 https://www.bkduck.cn][id]
[id]: https://www.bkduck.cn/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值