先在项目的根目录下复制一份 backend 为 api:

1
cp backend/ api -r

拷贝 api 环境

1
2
cp -a environments/dev/frontend environments/dev/api
cp -a environments/prod/frontend environments/prod/api

修改 environments/index.php 文件之后的代码(主要是添加了一些 api 相关的代码):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
return [
    'Development' => [
        'path' => 'dev',
        'setWritable' => [
            'backend/runtime',
            'backend/web/assets',
            'frontend/runtime',
            'frontend/web/assets',
            'api/runtime',
            'api/web/assets',
        ],
        'setExecutable' => [
            'yii',
        ],
        'setCookieValidationKey' => [
            'backend/config/main-local.php',
            'frontend/config/main-local.php',
            'api/config/main-local.php',
        ],
    ],
    'Production' => [
        'path' => 'prod',
        'setWritable' => [
            'backend/runtime',
            'backend/web/assets',
            'frontend/runtime',
            'frontend/web/assets',
            'api/runtime',
            'api/web/assets',
        ],
        'setExecutable' => [
            'yii',
        ],
        'setCookieValidationKey' => [
            'backend/config/main-local.php',
            'frontend/config/main-local.php',
            'api/config/main-local.php',
        ],
    ],
];

然后再执行初始化命令:

1
php init

然后记得去 common/config/bootstrap.php 最后一行添加如下代码:

1
Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');

修改一下配置文件 api/config/main.php

1
2
3
4
5
return [
    'id' => 'app-api',
    // ...
    'controllerNamespace' => 'api\controllers',
]

最后 api 里面的控制器等有命名空间的文件也要修改一下。

参考资料