yii2 - urlmanager路由无法正常工作

时间:2014-11-26 08:02:47

标签: php yii2

这里我使用了带规则的yii2配置

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-backend',
    'basePath' => dirname(__DIR__),
    'controllerNamespace' => 'backend\controllers',
    'bootstrap' => ['log'],
    'modules' => [],
    'components' => [
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],  
        'urlManager' => [
                'enablePrettyUrl' => true,
                'rules' => require(__DIR__ . '/routes.php'), 
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ],
    'params' => $params,
];

并在下面给出routes.php

<?php
use yii\web\UrlRule;
return array(
// REST routes for CRUD operations
'POST <controller:\w+>s' => '<controller>/create', // 'mode' => UrlRule::PARSING_ONLY will be implicit here
'api/<controller:\w+>s' => '<controller>/index',
'PUT api/<controller:\w+>/<id:\d+>' => '<controller>/update',// 'mode' => UrlRule::PARSING_ONLY will be implicit here
'DELETE api/<controller:\w+>/<id:\d+>' => '<controller>/delete', // 'mode' => UrlRule::PARSING_ONLY will be implicit here
'api/<controller:\w+>/<id:\d+>' => '<controller>/view',
// normal routes for CRUD operations
'<controller:\w+>s/create' => '<controller>/create',
'<controller:\w+>/<id:\d+>/<action:update|delete>' => '<controller>/<action>',
); 

当我访问local2host.com/advanced/backend/web/index.php/country/create时 - 它工作正常

但是当我通过local2host.com/advanced/backend/web/index.php/api/country/create

访问时

它正在抛出404 - 未找到错误

无法解析请求“api / country / create”。

根据我的要求: 当我访问此链接local2host.com/advanced/backend/web/index.php/api/country/create  它应该访问“country”作为控制器并“创建”作为动作

1 个答案:

答案 0 :(得分:2)

看来你有模块。首先,您需要将api模块添加到配置文件中:

'modules' => [
    'api'
],

其次,您需要将模块添加到您的规则中,如下所示:

'<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>',
'<module:\w+><controller:\w+>/<action:update|delete>/<id:\d+>' => '<module>/<controller>/<action>',

值得注意的是,您可能需要使用模块处理其他规则并拥有自己的自定义规则。