Yii2 Rest API 具有多个控制器的额外模式

Yii2 Rest API extra patterns with multiple controllers

我的 API 中有 2 个控制器。每个都有额外的模式定义。除了在额外模式中定义的用户登录外,我的所有操作都正常工作。

<?
'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        [
            'class' => 'yii\rest\UrlRule',
            'controller' => [ 'v1/item', 'v1/user'], 
            'tokens' => [
                '{id}' => '<id:\w+>', //commenting out this token allows login to return
                '{type}'=>'<type:\w+>'
            ],
            'extraPatterns' => [
                'POST {id}/image/{type}' => 'image', //from the item controller
                'GET login' => 'login' // from the USER controller
            ]
        ]

    ],
],

user/login 错误也是如此。请注意,它正在寻找 v1/user/view 操作

 {
    "name": "Not Found",
    "message": "Page not found.",
    "code": 0,
    "status": 404,
    "type": "yii\web\NotFoundHttpException",
    "previous": {
        "name": "Invalid Route",
        "message": "Unable to resolve the request: v1/user/view",
        "code": 0,
        "type": "yii\base\InvalidRouteException"
    }
}

如果我在 urlManager 中注释掉 ID 令牌,user/login 操作有效,但我的其他路由失败。

通过将规则分成每个控制器的一个项目来解决:

[
    'class' => 'yii\rest\UrlRule',
    'controller' => 'v1/config', //, 
    'tokens' => [
        '{id}' => '<id:\w+>',
        '{type}'=>'<type:\w+>'
    ],
    'extraPatterns' => [
        'POST {id}/image/{type}' => 'image',
    ]
],

[
    'class' => 'yii\rest\UrlRule', 
    'controller' => 'v1/user', 
    'extraPatterns' => [
        'GET login' => 'login'
    ],
] 

当您指定令牌时

'{id}' => '<id:\w+>',

您覆盖默认 yii\rest\UrlRule 个标记

'{id}' => '<id:\d[\d,]*>',

and view route start 转化为following

'GET,HEAD {id}' => 'view',
/user/<id:\w+>

其中 id 是一个词,因此 /user/login 被翻译成查看操作