php – Yii2 REST API作为模块路由配置

我有一个现有的Yii2应用程序,并且一直在尝试将REST API作为一个额外的模块实现(也许一个模块不是正确的方法吗?)但是我在配置路由结构时遇到了一些麻烦.根据
following guide,它没有完全奏效,也没有遵循预期的结果.

我已经构建了一个如下所示的附加模块:

module
  api
    controllers
      UserController.php
    Module.php

UserController.php

<?php

namespace app\modules\api\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController
{
    public $modelClass = 'app\models\User';
}

Module.php

<?php

namespace app\modules\api;

/**
 * onco module definition class
 */
class Module extends \yii\base\Module
{
    public $defaultController = 'user';
    /**
     * @inheritdoc
     */
    public $controllerNamespace = 'app\modules\api\controllers';

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        // custom initialization code goes here
    }
}

在我的配置文件中,我添加了以下内容:

'request' => [
    ...
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ]
        ],
    ...
    'urlManager' => [
      'enablePrettyUrl' => true,
        'showScriptName' => false,
        'enableStrictParsing' => false, // have tried as true also
    'rules' => [
     ...
     ['class' => 'yii\rest\UrlRule', 'controller' => '\app\modules\api\controllers\user'],
            ],
     ],
     ...
     'modules' => [
      ...
      'api' => [ // module for RESTful API
            'class' => 'app\modules\api\Module',
        ],
    ]

当我通过邮递员运行以下网址时,我得到以下内容:

> http://localhost/site1/web/api/users – > 404
> http://localhost/site1/web/api/users/index – > 404
> http://localhost/site1/web/api/user/index – >返回json repsonse
> http://localhost/site1/web/api/user/2 – > 404

我不确定为什么在文档中注明的预测路线为:

Trying it Out With the above minimal amount of effort, you have
already finished your task of creating the RESTful APIs for accessing
the user data. The APIs you have created include:
GET /users: list all users page by page;

HEAD /users: show the overview information of user listing;

POST /users: create a new user;

GET /users/123: return the details of the user 123;

HEAD /users/123: show the overview information of user 123;

PATCH /users/123 and PUT /users/123: update the user 123;

DELETE /users/123: delete the user 123;

OPTIONS /users: show the supported verbs regarding endpoint /users;

OPTIONS /users/123: show the supported verbs regarding endpoint /users/123

我在这个设置中可能做错了什么?有没有更好的方法将API实施到现有网站,同时保持DRY实践?

最佳答案 试试这个:

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
         [
            'class' => 'yii\rest\UrlRule', 
            'controller' => ['api/user'],
         ]
    ]
],
...
'modules' => [
  ...
  'api' => [
        'basePath' => '@app/modules/api',
        'class' => 'app\modules\api\Module',
    ],
]

另外一定要实现prettyUrl的related server server configs.

点赞