API interface development for Yii2advanced is based on RESTful architecture configuration, implementation, and testing

Source: Internet
Author: User
Tags findone
: This article mainly introduces the configuration, implementation, and testing of Yii2advanced API interface development based on the RESTful architecture. if you are interested in PHP tutorials, refer to it. Environment configuration:

Enable pseudo-static server

Take apache as an example. check httpd. conf in the conf directory of apache and find the following code:

LoadModule rewrite_module modules/mod_rewrite.so

Remove the # above it. if not found, add it.

Find the code

 
      AllowOverride All    Options None    Require all granted
 

Change the original AllowOverride None to AllowOverride All.

Create a. htaccess file under the root directory of the site. the content is as follows:

 
    Options +FollowSymlinks  RewriteEngine On  RewriteCond %{REQUEST_FILENAME} !-d  RewriteCond %{REQUEST_FILENAME} !-f  RewriteRule . index.php
 

. Htaccess

I will not describe the configuration of yii2 here. if necessary, read the YII2 Practice Manual.

YII2 actual operations:

1. configure URL rules and modules

(1) create a new modules folder and implement api version control. For example, V1 and V2 ......

Create the controllers folder (controller), models folder (model), and Module. php configuration files under the v1 folder.

The Module. php file is as follows:

1
 

Lines 2nd and 7th change with version extension (v1-> v2 ...).

(2) configure the main. php file in the config folder.

1
  'App-api', 6 'basepath' => dirname (_ DIR _), 7 'bootstrap '=> [8 'log' 9], 10 'modules' => [11 'v1 '=> [12 'class' => 'api \ modules \ v1 \ module' 13], 14 'V2' => [15 'class' => 'api \ modules \ v2 \ module' 16] 17], 18 'controllernamespace '=> 'api \ controllers ', 19 'components' => [20 'user' => [21 'identityclass' => 'common \ models \ user', 22 'enablesautologin' => false, 23 'enablessession '=> false, 24 'loginurl' => Null25], 26 'urlmanager' => [27 'enableprettyurl' => true, // enable beautify URL28 'enablestrictparsing' => true, // whether to perform strict url resolution 29 'showscriptname' => false, // check whether the script entry file 30' rules' => [31 [32 'class' => 'yii \ rest \ urlrule' is displayed in the URL path ', 33 'controller' => [34 'v1/site '35] 36], 37 [38 'class' => 'yii \ rest \ urlrule ', 39 'controller' => [40 'v2/site' 41] 42] 43] 44], 45 'log' => [46 'tracelevel '=> YII_DEBUG? 3: 'targets' => [48 [49 'class' => 'yii \ log \ filetarget', 50' levels' => [51 'error ', 52 'warning' 53] 54] 55] 56], 57 'errorhandler' => [58 'erroraction' => 'site/error' 59] 60], 61 'params' => $ params62];

Main. php

Note 10 ~ 17 rows, 20 ~ I believe you will understand the 44-line component configuration after reading it carefully. I will not repeat the principles here. please pay special attention to the 33 ~ The 35-line code indicates the v1/site Controller. as the interface controller increases, you can directly add it to the array. This article strives to quickly configure the implementation of the RESTful architecture.

(3) v2 and v3 indicate later version changes. configurations are similar to the v1 folder.

2. create a model

Prepare a data table named mxq_guide for the database.

Create table 'mxq _ Guide' ('id' int (11) not null AUTO_INCREMENT, 'imgurl' varchar (255) defaultnull comment 'image path ',
'Status' int (11) defaultnull comment '1 enable 0 disabling ',
'Flag' int (11) defaultnull comment '1 Android 2 apple ',
Primary key ('id ')
) ENGINE = MyISAM AUTO_INCREMENT = 24 default charset = utf8 COMMENT = 'app Navigator ';

After creation, add several pieces of data to the database in time.

Create a guide. php model using scaffolding gii (see the yii2 authoritative guide for usage ). The generated file must be rewritten to meet the RESTful requirements in the following format. Then, transfer the data from the models folder to the v1/models folder, and pay attention to the modification of the namespace.

 1 
   $token23        ]);24    }2526publicfunction getId()27    {28return$this->id;29    }3031publicfunction getAuthKey()32    {33return$this->authKey;34    }3536publicfunction validateAuthKey($authKey)37    {38return$this->authKey === $authKey;39    }4041publicstaticfunction findIdentity($id)42    {43returnstatic::findOne($id);44    }4546publicstaticfunction tableName()47    {48return '{{%guide}}';49    }5051publicfunction rules()52    {53return [54            [55                [56                     'imgurl',57                     'status',58                     'flag'59                 ],60                 'required'61             ],62            [63                [64                     'status',65                     'flag'66                 ],67                 'integer'68             ],69            [70                [71                     'imgurl'72                 ],73                 'string',74                 'max' => 25575            ]76        ];77    }7879publicfunction attributeLabels()80    {81return [82             'id' => Yii::t('app', 'ID'),83             'imgurl' => Yii::t('app', 'imgurl'),84             'status' => Yii::t('app', 'status'),85             'flag' => Yii::t('app', 'flag')86        ];87    }88 }

Guide. php

3. create a controller

1
  'Yii \ rest \ serializer', 17' collectionEnvelope '=> 'items '18]; 1920 // public function behaviors () 21 // {22 // $ behaviors = parent:: behaviors (); 23 // $ behaviors ['authenticator'] = [24 // 'class' => CompositeAuth: className (), 25 // 'authmethods '=> [26 // QueryParamAuth: className () 27 //] 28 //]; 29 // return $ behaviors; 30 //} 31 publicfunction actions () 32 {33 $ actions = parent: actions (); 34 // deregister the implemented party of the system Method 35 unset ($ actions ['index'], $ actions ['update'], $ actions ['create'], $ actions ['delete'], $ actions ['View']); 36 return $ actions; 37} 3839 publicfunction actionIndex () 40 {41 $ modelClass = $ this-> modelClass; 42 $ query = $ modelClass:: find (); 43 returnnew ActiveDataProvider ([44 'query' => $ query45]); 46} 4748 publicfunction actionCreate () 49 {50 $ model = new $ this-> modelClass (); 51 // $ model-> load (Yii: $ app-> getRequest () 52 //-> getBodyParams (), ''); 53 $ model-> attributes = Yii: $ app-> request-> post (); 54if (! $ Model-> save () {55returnarray_values ($ model-> getFirstErrors () [0]; 56} 57 return $ model; 58} 5960 publicfunction actionUpdate ($ id) 61 {62 $ model = $ this-> findModel ($ id); 63 $ model-> attributes = Yii: $ app-> request-> post (); 64if (! $ Model-> save () {65returnarray_values ($ model-> getFirstErrors () [0]; 66} 67 return $ model; 68} 6970 publicfunction actionDelete ($ id) 71 {72 return $ this-> findModel ($ id)-> delete (); 73} 7475 publicfunction actionView ($ id) 76 {77 return $ this-> findModel ($ id); 78} 7980 protectedfunction findModel ($ id) 81 {82 $ modelClass = $ this-> modelClass; 83if ($ model = $ modelClass: findOne ($ id ))! = Null) {84 return $ model; 85} else {86 thrownew NotFoundHttpException ('The requested page does not exist. '); 87} 88} 8990 publicfunction checkAccess ($ action, $ model = null, $ params = []) 91 {92 // check whether the user can access $ action and $ model93 // if the access is denied, ForbiddenHttpException94 // var_dump ($ params); exit; 95} 96} should be thrown}

SiteController. php

Create a controller in the modules/controllers folder and note the modifications to the namespace.

Note that the Controller here is different from the general Controller that inherits the Controller, and the ActiveController class must be inherited here.

20 ~ The code with 30 lines of comments is based on the access_token authentication of the RESTful architecture. it has not been tested yet and will be supplemented later.

Now, all configurations based on YII2 have been basically completed. next we will introduce the api testing tools and methods.

RESTful test tool PostMAN:

The postman plug-in is a practical plug-in that simulates requests based on Google's browser. The specific usage is involved in the following testing process. sorry for the shortcomings. I am also using it for the first time.

We recommend that you use the above APP version to encapsulate your own APIs. The following is the web version.

YII2 supports four RESTful request methods: GET to view information, POST to create information, PUT to update information, and DELETE to DELETE information.

The following describes four data request methods. (This is just a demonstration of the effect. you need to explore it yourself .)

This example shows how to request data from the database using the GET method. Corresponding to the modules/controllers/SiteController/actionIndex method.

Please pay attention to the URL address in the top box. by default, the rest controller performs the plural request http://api.mxq.com/v1/sites, which refers to the restful rule.

If an error occurs, you can go to the YII authority guide to check the cause of the error.

The ActiveController of YII2 achieves data paging by default.

The POST method is used to create database data. Corresponding to the modules/controllers/SiteController/actionCreate method.

If a data validation rule is written at the data layer of the database, an error is displayed when the submitted data does not meet the requirements. This is also one of the advantages of REST. For example, in the following case, flag is defined as the int type:

Next we will demonstrate how to update the database data using the PUT method. Corresponding to the modules/controllers/SiteController/actionUpdate method.

Here, please pay attention to the top URL: http://api.mxq.com/v1/sites/15 here 15 represents the Database id for 15 data, indicating to update the database ID for 15 data information. Please note. When using the update and delete data operations, RESTful IDs cannot be submitted in the form of a form, and must be followed by the URL.

Next we will demonstrate how to DELETE the database data using the DELETE method. It corresponds to the modules/controllers/SiteController/actionDelete method.

When the return value is 1, the deletion operation is successful. Take a closer look at the functions in the sitecontroller.

The above are some brief introductions, implementation methods, and test results of RESTful based on yii2. You are welcome to add anything that is incorrect or missing. It will also be updated later on this basis. I first came into contact with the yii2 framework and RESTful architecture. if there is anything wrong with it, please forgive me.

The above describes the configuration, implementation, and testing of the RESTful architecture-based API interface development for Yii2 advanced edition, including some content. I hope my friends who are interested in the PHP Tutorial will be helpful.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.