Yii2.0 RESTful Web Services (3)

Source: Internet
Author: User
Tags yii

After creating the resource class and specifying the resource grid output, the next step is to create a controller action to expose the resource to the end user through RESTful APIs.

YII provides two controller base classes to simplify the work of creating restful operations: Yii\rest\controller and Yii\rest\activecontroller, The difference between the two classes is that the latter provides a series of operations to process resources into ActiveRecord (about ActiveRecord) . So if using ActiveRecord built-in operations would be convenient, consider inheriting the controller class Yii\rest\activecontroller, which will allow you to complete powerful restful APIs with minimal code.

Yii\rest\activecontroller provides additional features:

  • A series of common operations:index,view,create,update,delete,options;
  • User authentication of operations and resources.
Create a Controller class

When creating a new controller class, the name of the controller class is best used in the singular format of the resource name, for example, the controller that provides the user information can be named usercontroller .

Create new operations and create actions in Web apps like, the only difference is that the web app calls render () method renders a view as the return value and returns data directly for restful operations, Yii\rest\controller: Serializer (about serializer) and yii\web\response handle the conversion of the raw data to the request format, such as

publicfunction actionView($id){    return User::findOne($id);}
Filter filters

Most restful API features provided by Yii\rest\controller are implemented through filters. In particular, the following filters are executed sequentially:

    • Yii\filters\contentnegotiator
    • Yii\filters\verbfilter
    • Yii\filters\authmethod
    • Yii\filters\ratelimiter

These filters are declared in the Yii\rest\controller::behaviors () method, which can be overridden to configure a separate filter, disabling one or adding your own custom filters. For example, if you only want to use HTTP Basic authentication, you can write the following code:

 Use Yii\Filters\Auth\Httpbasicauth; Public  function behaviors() {$behaviors =Parent:: Behaviors (); $behaviors [' Authenticator '] = [' class '= Httpbasicauth::classname (),];return$behaviors;}
Inherited ActiveController

If your controller inherits Yii\rest\activecontroller, you should set the Yii\rest\activecontroller::modelclass property to the resource class name that is returned to the user through the controller, which must inherit yii\db\ ActiveRecord.

Custom Actions

Yii\rest\activecontroller provides the following by default:

    • yii\rest\indexaction: List resources by page;
    • yii\rest\viewaction: Returns details of the specified resource;
    • yii\rest\createaction: Create a new resource;
    • yii\rest\updateaction: Update an existing resource;
    • yii\rest\deleteaction: Deletes the specified resource;
    • yii\rest\optionsaction: Returns the supported HTTP methods.

All of these actions are declared by the Yii\rest\activecontroller::actions () method, which overrides the actions() method configuration or disables these operations as follows:

 Public  function actions() {$actions =Parent:: Actions ();//Disable the "delete" and "create" actions    unset($actions [' Delete '], $actions [' Create ']);//Use the "Preparedataprovider ()" method to customize the data provider$actions [' index '][' Preparedataprovider '] = [$this,' Preparedataprovider '];return$actions;} Public  function preparedataprovider() {//prepare and return data for the "index" Operation provider}


Perform an access check

When displaying data through RESTful APIs, it is often necessary to check whether the current user has permission to access and manipulate the requested resource, which can be overridden in Yii\rest\activecontroller yii\rest\ The Activecontroller::checkaccess () method to complete the permission check.

/** * Checks the privilege of the current user. Check the permissions of the currently users * * TH Is method should was overridden to check whether the current user have the privilege * to run the specified action against T He specified data model. * If The user does not has access, a forbiddenhttpexception should be thrown. * This method should be overwritten to check whether the current user has permission to perform the specified operation to access the specified data model * If the user does not have permission, a forbiddenhttpexception exception should be thrown * *  @param  string $action The ID of the action to be executed *  @param  \yii\base\model $model the Model to being accessed. If NULL, it means no specific model is being accessed. *  @param  array $params Additional parameters *  @throws  forbiddenhttpexception If the user does not has access */ Public  function checkAccess($action, $model = null, $params = []) {//Check whether users can access $action and $model    //Access denied should be thrown forbiddenhttpexception}

checkAccess()The method is called by default by the Yii\rest\activecontroller default action, and should be explicitly called in a new operation if you create a new operation and want to perform a permission check.


Compared to the restful style of the laravel framework, YII has much higher levels of restful packaging, such as the Declaration of interfaces,Laravel need to spend more time on routing settings, The way of Yii is more inclined to the MVC side of the MVC, the controller is always dominant, because it covers the basic curd operation, so the implementation of the single table operation is very simple.

The restful control implemented by Yii is implemented by overloading the Activecontroller::checkAccess (), but Laravel is through a policy setting, Then in the Authserviceprovider implementation, each step corresponding to the time will be checked for its security, this is also with the ROR multi-contract less configuration of the idea of matching.

Yii2.0 RESTful Web Services (3)

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.