Yii2.0 RESTful API version control

I have written two articles about how Yii2.0 RESTful apis are built and authenticated. However, version management is not covered. Today, I will talk about how to implement version management.

Simply start from scratch to build it step by step, but about some concepts and use of this article will not be explained, you can refer to the first Yii2.0 RESTful API basic configuration tutorial for configuration

Install Yii2.0

Install by Composer

This is the preferred way to install Yii2.0. If you haven’t already installed Composer, you can follow the instructions here.

After installing Composer, run the following command to install the Composer Asset plugin:

composer global require FXP "composer - asset - the plugin: ^ 1.2.0"
Copy the code

To install the advanced application template, run the following command:

Composer Create-Project Yiisoft/Yii2-app - Advanced YII-API 2.0.14Copy the code

Copy the backend directory and name it API

Open API \config\main.php to change the id. ControllerNamespace:

return [
    'id'= >'app-api'.'basePath' => dirname(__DIR__),
    'controllerNamespace'= >'api\controllers',]Copy the code

Example Initialize an advanced template

Take a look at this article before you initialize it

cd advanced
php init
Copy the code

Open common config main. PHP to enable url route beautification rules

'urlManager'= > ['enablePrettyUrl'= >true.'showScriptName'= >false.'rules'= > []],Copy the code

Open common\config\bootstrap.php to add the following aliases

Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
Copy the code

Ok, the above work is ready, then enter the topic, about the version of more introduction can refer to the authoritative guide, here but more explanation (PS: mainly I will not……)

The version of Yii2 can be understood as different modules, and each version is a new module, such as common V1, V2 and so on.

Module construction

As for how to generate modules, we can use GII to do this.

Configuration GII

Open the API /config/main-local.php file and change it as follows:

if(! YII_ENV_TEST) { // configuration adjustmentsfor 'dev' environment
    $config['bootstrap'=] []'debug';
    $config['modules'] ['debug'] = [
        'class'= >'yii\debug\Module',];$config['bootstrap'=] []'gii';
    $config['modules'] ['gii'] = [
        'class'= >'yii\gii\Module'.'allowedIPs'= > ['127.0.0.1'.The '*']]. }Copy the code

‘allowedIPs’ => [‘127.0.0.1’, ‘*’], otherwise there will be Forbidden (#403), you can configure it according to your own needs. Or not configured

Generated Modules

Enter http://your host/gii in your browser to see the Module Generator. Click Start

Modules Class 中输入:api\modules\v1\Module

Enter v1 in Module ID (normally automatically entered)

Click on the Preview

Finally, click Generate

Configuration module

Open the API /config/main.php file and modify modules

'modules'= > ['v1'= > ['class'= >'api\modules\v1\Module',]],Copy the code

Then modify the urlManager

'urlManager'= > ['enablePrettyUrl'= >true.'enableStrictParsing'= >true.'showScriptName'= >false.'rules' => [
        ['class'= >'yii\rest\UrlRule'.'controller'= >'v1/default'.'extraPatterns'= > ['GET index'= >'index'[,], [,],Copy the code

Based on the above, Yii2.0 RESTFul API achieves version management, which can be accessed through the following address:

http://localhost/v1/defaults
Copy the code

The address above me is already mapped to the API/Web directory, please configure it according to your actual situation

If you open the modules directory, you can see that there is a v1 directory, and you can see that there is a controllers directory, and there is a views directory. The defaults we just accessed are those two files. The controller renders the view just like a traditional Web project

Well, as you probably know, we’ll put our controller code in modules/v1/controllers from now on

Just the default GII generated code for us, because we are API, so the views directory, we generally do not use.

Create a new REST controller and create a new UserController under Modules \v1\controllers

<? php namespace api\modules\v1\controllers; use yii\rest\Controller; /** * User controllerfor the `v1` module
 */
class UserController extends Controller
{
    /**
     * @return string
     */
    public function actionIndex()
    {
        return 'this is v1/user'; }}Copy the code

Modify urlManager in API /config/main.php

'urlManager'= > ['enablePrettyUrl'= >true.'enableStrictParsing'= >true.'showScriptName'= >false.'rules' => [
        ['class'= >'yii\rest\UrlRule'.'controller'= >'v1/default'.'extraPatterns'= > ['GET index'= >'index',]], ['class'= >'yii\rest\UrlRule'.'controller'= >'v1/user'.'extraPatterns'= > ['GET index'= >'index'[,], [,],Copy the code

Give it a try

http://localhost/v1/users/index
Copy the code

Ok, that’s how Yii2.0 version management is implemented

Formatted response

Modify API /config/main.php to add Response to components array

'response'= > ['class'= >'yii\web\Response'.'on beforeSend'= >function ($event) {
        $response = $event->sender;
        $response->data = [
            'success'= >$response->isSuccessful,
            'code'= >$response->getStatusCode(),
            'message'= >$response->statusText,
            'data'= >$response->data,
        ];
        $response->statusCode = 200; },].Copy the code

So far, I have completed three articles about Yii2.0 RESTFul API, which are as follows:

Yii2.0 RESTful API Basic configuration tutorial

Yii2.0 RESTful API Authentication Tutorial

Yii2.0 RESTful API version control

Write really not how, if you see the harvest, might as well leave a message to a comment, or you feel that write a problem, or do not understand, you can also leave a message, we can discuss research together.