Yii2 is developed, configured, implemented, and tested based on the advanced API interface of the RESTful architecture. yii2restful

Source: Internet
Author: User
Tags findone

Yii2 is developed, configured, implemented, and tested based on the advanced API interface of the RESTful architecture. yii2restful
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

<Directory "C:/phpStudy/Apache/cgi-bin">    AllowOverride All    Options None    Require all granted</Directory>

Change the original AllowOverride None to AllowOverride All.

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

<IfModule mod_rewrite.c> Options + FollowSymlinks RewriteEngine On RewriteCond % {REQUEST_FILENAME }! -D RewriteCond % {REQUEST_FILENAME }! -F RewriteRule. index. php </IfModule>. Htaccess

The configuration of yii2 is not described here.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 <?php 2 namespace api\modules\v1; 3  4 class Module extends \yii\base\Module 5 { 6  7     public $controllerNamespace = 'api\modules\v1\controllers'; 8  9     public function init()10     {11         parent::init();12     }13 }

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

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

1 <? Php 2 $ params = array_merge (require (_ DIR __. '/.. /.. /common/config/params. php '), require (_ DIR __. '/.. /.. /common/config/params-local.php '), require (_ DIR __. '/params. php '), require (_ DIR __. '/params-local.php'); 3 4 return [5 'id' => '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 'enablesession' => false, 24 'loginurl' => null25], 26 'urlmanager' => [27 'enableprettyurl' => true, // enable beautifying URL28 'enablestrictparsing' => true, // whether to perform strict url Parsing 29 'showscriptname' => false, // in UR L whether or not the script entry file 30'rules' => [31 [32 'class' => 'yii \ rest \ urlrule' is displayed in the 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) default null 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.

Use the scaffold gii to create the guide. php model.Yii2 authoritative guide). 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 <? Php 2 namespace api \ modules \ v1 \ models; 3 4 use Yii; 5 use yii \ db \ ActiveRecord; 6 use yii \ web \ IdentityInterface; 7 8/** 9 * This is the model class for table "{{% guide }}". 10*11 * @ property integer $ id12 * @ property string $ imgurl13 * @ property integer $ status14 * @ property integer $ flag15 */16 class Guide extends ActiveRecord implements IdentityInterface17 {18 19 public static function findIdentityByAccessToken ($ token, $ type = null) 20 {21 return static: findOne ([22 'Access _ token' => $ token23]); 24} 25 26 public function getId () 27 {28 return $ this-> id; 29} 30 31 public function getAuthKey () 32 {33 return $ this-> authKey; 34} 35 36 public function validateAuthKey ($ authKey) 37 {38 return $ this-> authKey ===$ authKey; 39} 40 41 public static function findIdentity ($ id) 42 {43 return static: findOne ($ id ); 44} 45 46 public static function tableName () 47 {48 return '{% guide}'; 49} 50 51 public function rules () 52 {53 return [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} 78 79 public function attributeLabels () 80 {81 return [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. php3. Create a controller 1 <? Php 2 namespace api \ modules \ v1 \ controllers; 3 4 use Yii; 5 use yii \ rest \ ActiveController; 6 use yii \ filters \ auth \ CompositeAuth; 7 use yii \ filters \ auth \ QueryParamAuth; 8 use yii \ data \ ActiveDataProvider; 9 10 class SiteController extends ActiveController11 {12 13 public $ modelClass = 'api \ modules \ v1 \ models \ Guide '; 14 15 public $ serializer = [16 'class' => 'yii \ rest \ serializer', 17 'collectionenvelope' => 'Items '18]; 19 20 // 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 public function actions () 32 {33 $ actions = parent: actions (); 34 // unset ($ actions ['index'], $ actions [' Update'], $ actions ['create'], $ actions ['delete'], $ actions ['view']); 36 return $ actions; 37} 38 39 public function actionIndex () 40 {41 $ modelClass = $ this-> modelClass; 42 $ query = $ modelClass: find (); 43 return new ActiveDataProvider ([44 'query' => $ query45]); 46} 47 48 public function actionCreate () 49 {50 $ model = new $ this-> modelClass (); 51 // $ model-> load (Yii: $ app-> getRequest () 52 //-> getBodyParams (), ''); 53 $ model-> attributes = Yii ::$ app-> request-> post (); 54 if (! $ Model-> save () {55 return array_values ($ model-> getFirstErrors () [0]; 56} 57 return $ model; 58} 59 60 public function actionUpdate ($ id) 61 {62 $ model = $ this-> findModel ($ id); 63 $ model-> attributes = Yii :: $ app-> request-> post (); 64 if (! $ Model-> save () {65 return array_values ($ model-> getFirstErrors () [0]; 66} 67 return $ model; 68} 69 70 public function actionDelete ($ id) 71 {72 return $ this-> findModel ($ id)-> delete (); 73} 74 75 public function actionView ($ id) 76 {77 return $ this-> findModel ($ id); 78} 79 80 protected function findModel ($ id) 81 {82 $ modelClass = $ this-> modelClass; 83 if ($ model = $ modelClass: findOne ($ id ))! = Null) {84 return $ model; 85} else {86 throw new NotFoundHttpException ('the requested page does not exist. '); 87} 88} 89 90 public function 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 goYII authoritative guide-ErrorCheck 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.

 

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.