YII2 configuration, implementation, testing, yii2restful_php tutorials for advanced API interface development based on restful architecture

Source: Internet
Author: User
Tags findone

YII2 configuration, implementation, and testing of Advanced API interface based on restful architecture, yii2restful


Environment configuration:

Turn on server pseudo-static

For Apache, for example, look at Apache's conf directory under httpd.conf and find the following code

LoadModule Rewrite_module modules/mod_rewrite.so

Remove the # in front of it and add it if it is not found.

Find the code, please.

 
  
  
       allowoverride all    Options None    
  
   Require all
  
    granted
 
  

Change the original allowoverride none to allowoverride all.

Then create a. htaccess file under the site root, with the following content:

Options + followsymlinks rewriteengine on Rewritecond %{request_filename}- D Rewritec Ond %{request_filename}- f rewriterule . Index. PHP . htaccess

Here no longer repeat the YII2 configuration, if necessary can see YII2 actual combat manual .

YII2 actual operation:

1. Configure URL rules and modules

(1) Create new modules folder and implement API interface version control. For example V1 version, V2 version ...

Under the V1 folder, create a new Controllers folder (Controller), Models folder (model), module.php configuration file.

The module.php file is as follows:

 
 1 
   PHP 2namespace api\modules\v1; 3 4 class extends \yii\base\module 5 {  6  7      Public $controllerNamespace = ' api\modules\v1\controllers '; 8 9      Public function Init () Ten     {one         parent::init ();  A     }

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

(2) Configuring the CONFIG. main.php file

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], Ten' Modules ' = [ One' V1 ' = [ A' Class ' = ' Api\modules\v1\module ' -], -' V2 ' = [ the' Class ' = ' Api\modules\v2\module ' - ] -], -' Controllernamespace ' = ' api\controllers ', +' Components ' = [ -' User ' = [ +' Identityclass ' = ' common\models\user ', A' Enableautologin ' = false, at' EnableSession ' = false, -' Loginurl ' = NULL -], -' Urlmanager ' = [ -' Enableprettyurl ' = true, // Enable beautify URLs -' Enablestrictparsing ' = true, // whether to perform strict URL parsing in' Showscriptname ' = false, // whether the script entry file is displayed in the URL path -' Rules ' = [ to [ +' Class ' = ' Yii\rest\urlrule ', -' Controller ' = [ the' V1/site ' * ] $], Panax Notoginseng [ -' Class ' = ' Yii\rest\urlrule ', the' Controller ' = [ +' V2/site ' A ] the ] + ] -], $' Log ' = [ $' TraceLevel ' = Yii_debug? 3:0, -' Targets ' = [ - [ the' Class ' = ' Yii\log\filetarget ', -' Levels ' = [ Wuyi' Error ', the' Warning ' - ] Wu ] - ] About], $' ErrorHandler ' = [ -' ErrorAction ' = ' site/error ' - ] -], A' Params ' = $params +]; main.php

Note 10~17 line, 20~44 line component configuration, I believe you can understand carefully read, here no longer repeat the principle, please pay special attention to 33~35 line of code, here is the V1/site controller, with the increase of interface controller, you can directly add in the array. This article seeks to quickly configure the implementation of a restful architecture.

(3) V2, V3 represents a later version change, the configuration is similar to the V1 folder.

2. Create a model

Database to prepare a data table named Mxq_guide

CREATE TABLE ' mxq_guide ' (  ' id ' int (NULL auto_increment,  ' imgurl ' varchar (  DEFAULTCOMMENT ' picture path ',
' Status ' int (DEFAULTNULL COMMENT ' 1 Enable 0 disable ',
' Flag ' int (DEFAULTNULL COMMENT ' 1 android 2 Apple ',
KEY
ENGINEDEFAULT charset=utf8 comment= ' app navigation map ';

After creating, be careful to add a few data information to the database in time.

Create guide.php models using scaffolding GII (see the yii2 authoritative guide for usage). After the generated file is overwritten, modify it to the following form to meet restful needs. Then move from the Models folder to the V1/models folder, and note the changes to 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 was the model class for table "{{%guide}}". Ten * One * @property integer $id A * @property string $imgurl - * @property integer $status - * @property integer $flag the */ - classGuide extendsActiveRecord Implements Identityinterface - { - + Public Static functionFindidentitybyaccesstoken ( $token, $type= NULL ) - { + return Static:: FindOne ([ A' Access_token ' = $token at ]); - } - - Public function getId () - { - return $this- ID; in } - to Public function Getauthkey () + { - return $this- AuthKey; the } * $ Public functionValidateauthkey ( $authKey ) Panax Notoginseng { - return $this->authkey = = = $authKey ; the } + A Public Static functionFindidentity ( $id ) the { + return Static:: FindOne ( $id ); - } $ $ Public Static function TableName () - { - return' {{%guide}} ' ; the } - Wuyi Public function rules () the { - return [ Wu [ - [ About' Imgurl ', $' Status ', -' Flag ' -], -' Required ' A], + [ the [ -' Status ', $' Flag ' the], the' Integer ' the], the [ - [ in' Imgurl ' the], the' String ', About' Max ' = 255 the ] the ]; the } + - Public function attributelabels () the { Bayi return [ the' id ' = yii::t (' app ', ' ID '), the' Imgurl ' = yii::t (' app ', ' Imgurl '), -' Status ' = Yii::t (' app ', ' status '), -' Flag ' = yii::t (' app ', ' flag ' ) the ]; the } the} guide.php

3. 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 Ten classSitecontroller extends Activecontroller One { A - Public $modelClass= ' Api\modules\v1\models\guide ' ; - the Public $serializer= [ -' Class ' = ' Yii\rest\serializer ', -' Collectionenvelope ' = ' items ' - ]; + - // Public function Behaviors () + // { A //$behaviors = Parent::behaviors (); at //$behaviors [' authenticator '] = [ - //' class ' = Compositeauth::classname (), - //' authmethods ' = [ - //Queryparamauth::classname () - // ] - // ]; in //return $behaviors; - // } to Public function actions () + { - $actions= Parent:: actions (); the // the implementation method of the logout system's self-band * unset( $actions[' Index '], $actions[' Update '], $actions[' Create '], $actions[' Delete '], $actions[' View ' ]); $ return $actions ; Panax Notoginseng } - the Public function Actionindex () + { A $modelClass= $this- Modelclass; the $query= $modelClass:: find (); + return New Activedataprovider ([ -' Query ' = $query $ ]); $ } - - Public function actioncreate () the { - $model= New $this- Modelclass (); Wuyi // $model->load (Yii:: $app->getrequest () the //->getbodyparams (), '); - $model->attributes = Yii:: $app->request-> post (); Wu if(! $model- Save ()) { - return array_values( $model->getfirsterrors ()) [0 ]; About } $ return $model ; - } - - Public functionActionupdate ( $id ) A { + $model= $this->findmodel ( $id ); the $model->attributes = Yii:: $app->request-> post (); - if(! $model- Save ()) { $ return array_values( $model->getfirsterrors ()) [0 ]; the } the return $model ; the } the - Public functionActiondelete ( $id ) in { the return $this->findmodel ( $id), Delete (); the } About the Public functionActionview ( $id ) the { the return $this->findmodel ( $id ); + } - the protected functionFindmodel ( $id ) Bayi { the $modelClass= $this- Modelclass; the if(( $model= $modelClass:: FindOne ( $id)) !== NULL ) { - return $model ; -} Else { the Throw NewNotfoundhttpexception (' The requested page does not exist. ' ); the } the } the - Public functionCheckAccess ( $action, $model= NULL, $params= []) the { the // Check that users can access $action and $model the //Access denied should be thrown forbiddenhttpexception 94 //Var_dump ($params); exit; the } the} sitecontroller.php

Controller Please create the Modules/controllers folder and note the namespace modifications.

It is important to note that the controller here is different from the normal controller inheritance controllers, which need to inherit the Activecontroller class.

The code for the 20~30 line comment is based on the Access_token certification of the RESTful architecture, which has not yet been tested and subsequently supplemented.

At this point, all configurations based on YII2 have been basically completed, followed by the API interface testing tools and methods.

RESTful Test Tools Postman:

First introduce the Postman plug-in, is a Google browser based on a mock request of the utility plug-in. Specific use, in the following test process involved, the introduction of deficiencies please forgive me, I am also the first time to use.

It is recommended to use the above version of the app to facilitate subsequent encapsulation of their own written API interface, the following is the web version.

YII2 supports four ways of requesting: Get view information, post creation information, put update information, delete deletion information.

Here's how to start a demo of the four request data. (just demonstrate the effect, the specific use also need everyone to explore.) )

The data for the Get method request database is demonstrated here. The corresponding is the Modules/controllers/sitecontroller/actionindex method.

Please note the URL address in the topmost box, and rest defaults to the controller for the plural request http://api.mxq.com/v1/sites, which is the default rule for rest.

Playing * Asterisk position shows the normal effect, in the event of an error, you can go to yii authoritative guide-error check the cause of the error.

YII2 's Activecontroller By default implements the paging effect of the data.

The data for the new database is shown in the Post method. The corresponding is the Modules/controllers/sitecontroller/actioncreate method.

If data validation rules are written in the data layer of the database, the corresponding error is displayed when the submission data does not meet the requirements. This is one of the advantages of rest. For example, flag I define the int type as follows:

The next demonstration is that the Put method updates the database's data. The corresponding is 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 15 data, indicating the update database ID 15 data information. Please be careful. RESTful when using the update and delete data operations, the ID cannot be submitted as a form, and must immediately follow the URL.

The next demonstration is that the Delete method deletes the database data. The corresponding is the Modules/controllers/sitecontroller/actiondelete method.

When the return value of 1 indicates that the delete operation was executed successfully. Please observe the functions in the Sitecontroller controller carefully.

These are some simple introductions, implementation methods, and test results based on YII2 's restful. There is something wrong or missing where you are welcome to add. Subsequent updates will also be made on this basis. I first contact the YII2 framework and the restful structure, stating that if there is something wrong, please forgive us.

http://www.bkjia.com/PHPjc/1001458.html www.bkjia.com true http://www.bkjia.com/PHPjc/1001458.html techarticle YII2 configuration, implementation, testing, and yii2restful environment configuration for advanced API interface based on RESTful architecture: Turn on server pseudo-static This is the case for Apache, see Apache's conf directory ...

  • Related Article

    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.