Home > Article > PHP Framework > How to create an application in yii2
Application has two different meanings in yii2: application system and application subject. An application system can contain multiple application entities. A typical advanced application system such as yii2 advanced includes three application entities: frontend, backend and console, which respectively provide the frontend user interface, backend management interface and command line interface.
Sometimes, we also need an API to provide webservice. At this time we need to create a new application body to provide the API.
1, first copy a copy of backend in the root directory of the project and rename it to api: (Recommended learning: yii tutorial)
cp backend/ api -r
2, copy the api environment
cp -a environments/dev/frontend environments/dev/api cp -a environments/prod/frontend environments/prod/api
3, modify the code after the environments/index.php file (mainly adding some api-related code):
return [ 'Development' => [ 'path' => 'dev', 'setWritable' => [ 'backend/runtime', 'backend/web/assets', 'frontend/runtime', 'frontend/web/assets', 'api/runtime', 'api/web/assets', ], 'setExecutable' => [ 'yii', 'yii_test', ], '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', ], ], ];
4, switch to the project root directory, execute the initialization command
php init
Open cmd under windows, switch to the project root directory and execute the above command.
5, add the api folder alias, go to common/config/bootstrap.php and add the following code in the last line:
Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');
6, modify the configuration file api/config/main.php
return [ 'id' => 'app-api', // ... 'controllerNamespace' => 'api\controllers', ]
7. Modify the namespace of the files in the api file, controllers, models, assets, and views to api.
The above is the detailed content of How to create an application in yii2. For more information, please follow other related articles on the PHP Chinese website!