Example Analysis _php example of RESTful API principle in YII2

Source: Internet
Author: User
Tags auth extend smarty template yii

The principle of RESTful API in Yii2 is analyzed in this paper. Share to everyone for your reference, specific as follows:

A very important feature of YII2 is the default support for the Restful API, which enables a simple Restful API to the existing model via a few short configurations

Through the analysis of rest part of the source code, a simple analysis of the YII2 implementation of restful, and through a number of custom implementation of the association model RESTful API operations.

~ Represents the relationship of extends from

| | rest/
| | |-action.php ~ ' \yii\base\action '
| | |-controller.php ~ ' \yii\web\controller '
| | | |-activecontroller.php ~ ' Rest\controller '
| | |-serializer.php ~ ' yii\base\component '
| | |-urlrule.php ~ ' yii\web\compositeurlrule '
| | |-createaction.php ~ ' rest\action '
| | |-deleteaction.php ~ ' rest\action '
| | |-indexaction.php ~ ' rest\action '
| | |-optionsaction.php ~ ' rest\action '
| | |-updateaction.php ~ ' rest\action '
| | |-viewaction.php ~ ' rest\action '

1. Rest/controller ~ \yii\web\controller

Controller is the base class for RESTful API controller classes

It implements the following steps at a time in the control cycle of an API request 1~5:

① resolution of the content format of the response
② validation Request method
③ Verify user permissions
④ limit speed
⑤ format response data

Use Yii\filters\auth\compositeauth;
Use Yii\filters\contentnegotiator;
Use Yii\filters\ratelimiter;
Use Yii\web\response;
Use Yii\filters\verbfilter;
 /** * Controller is the base class for RESTful API Controller classes. * Controller implements the following steps in a RESTful API request handling Cycle * 1.
 Resolving response Format ([[[Contentnegotiator]]); * 2.
 Validating request method ([[Verbs ()]]. * 3.
 Authenticating User ([[\yii\filters\auth\authinterface]]); * 4.
 Rate limiting ([[ratelimiter]]); * 5. Formatting response data ([[Serializedata ()]] behaviors contentnegotiator Verbfilter Authenticator Ratelimite R afteraction Serializedata yii::createobject ($this->serializer)->serialize ($data) verbs [] */class Controller E
  Xtends \yii\web\controller {Public $serializer = ' Yii\rest\serializer ';
  Public $enableCsrfValidation = false; Public Function behaviors () {return [' Contentnegotiator ' => [' class ' =>
          Contentnegotiator::classname (), ' formats ' => [' Application/json ' => Response::format_json, ' Application/xml ' => response::format_xml,], ' verbfilter ' => [' class ' => Ver Bfilter::classname (), ' actions ' => $this->verbs (),], ' authenticator ' => [' class ' =& Gt
    Compositeauth::classname (),], ' ratelimiter ' => [' class ' => ratelimiter::classname (),],
  ]} public Function verbs () {return [];
  The Public Function Serializedata ($data) {return yii::createobject ($this->serializer)->serialize ($data);
    The Public Function afteraction ($action, $result) {$result = Parent::afteraction ($action, $result);
  return $this->serializedata ($result);

 }
}

2. Rest/activecontroller ~ Rest/controller

Activecontroller implements a series of restful methods for exchanging data with ActiveRecord.

The class name of the ActiveRecord is indicated by the Modelclass variable, yii\db\activerecordinterface???

By default, the following methods are supported:

*-' index ': List of models
*-' view ': Return the details of a model
*-' create ': Create a new model
*-' Update ': Update an existing model
*-' delete ': Delete an existing model
*-' options ': Return the Allowed HTTP methods

You can disable these default actions by overwriting actions () and unsetting responses.

To add a new action, overwrite the actions () to add a new action class to the end or a new action method

Notice that you also cover the verbs () method to declare that the new action supports those HTTP methods

You also need to overwrite checkaccess () to check whether the current user has permission to perform an action in response.

Write it again according to the instructions above Controller

Class Activecontroller extends Controller {public #modelClass;
  Public $updateScenario = Model::scenario_default;
  Public $createScenario = Model::scenario_default;
    Public Function init () {parent::init ();
    if ($this->modelclass = = null) {throw new Invalidconfigexception (' Modelclass ' property must is set. '); The Public Function actions () {return [' Index ' => [' class ' => ' App\controllers\rest\index
      Action ', ' Modelclass ' => $this->modelclass, ' checkaccess ' => [$this, ' checkaccess '],
      ' View ' ...
      ' Create ' ...
      ' Update ' ...
      ' Delete ' ...
  ' Options ' ...];
      } protected function verbs () {return [' Index ' => [' Get ', ' head '], ' view ' =>[' get ', ' head '],
  ' Create ' =>[' POST '], ' update ' =>[' put ', ' PATCH ', ' delete ' =>[' delete '];

 Public Function CheckAccess ($action, $model =null, $params = []) {}}

Here's how to implement a News controller that inherits from this rest\activecontroller:

namespace App\controllers;
Use App\controllers\rest\activecontroller; #刚才这个AC, I copied a copy of it from under Yii/rest
class Newscontroller extends Activecontroller
{public
  $modelClass = ' app\ Models\news ';
}

Defining it here is enough to implement the default method in Rest\activecontroller.
Below to cover, to implement a number of customized methods

Class Newscontroller extends Activecontroller {public $modelClass = ' app\models\news ';
  #定制serializer #public $serializer = ' Yii\rest\serializer ';
  Public $serializer = [' class ' => ' App\controllers\rest\serializer ', ' collectionenvelope ' => ' items ',]; Public Function Behaviors () {$be = Arrayhelper::merge (Parent::behaviors (), [' Verbfilter ' =& Gt
            [' Class ' => verbfilter::classname (), ' Actions ' => [' Index ' => [' get '],
        ...
          ]
            ], ' authenticator ' => [' class ' => compositeauth::classname (), ' Authmethods ' => [
          Httpbasicauth::classname (), Httpbearerauth::classname (), Queryparamauth::classname (),
          ]], ' contentnegotiator ' => [' class ' => contentnegotiator::classname (),
          ' Formats ' => [' text/html ' => response::format_html,]], ' Access ' => [' class ' => accesscontrol::classname (), ' Only ' => [' View '],
             ' Rules ' => [[' Actions ' => [' View '], ' Allow ' => false,
    ' Roles ' => [' @ '],],],];
  return $be;

 Public Function CheckAccess () {}}

3. Custom Actions

If you want to make big changes to the Actions, suggest a copy of it, do not use the original Yii\rest\xxxaction namespace

I'm here to make major changes to the goal of curd operations on related models.

Action

Before customizing each Action, look at their base class rest\action, which is primarily a Findmodel method

Class Action extend \yii\base\action
{public
  $modelClass;
  public $findModel;
  public $checkAccess;
  Public function init ()
  {
    if ($this->modelclass = = null) {
      throw new Invalidconfigexception Get_class ($ This). ':: $modelClass must be set ');
    }
  Public Function Findmodel ($id)
  {
    if ($this->findmodel!== null) {return
      Call_user_func ($this-> Findmodel, $id, $this);
    }
    $modelClass = $this->modelclass;
    $keys = $modelClass::p rimarykey ();
    if (count ($keys) > 1) {
      $values = explode (', ', $id);
      If..
    } ElseIf ($id!== null) {
      $model = $modelClass:: FindOne ($id);
    }
    if (Isset ($model)) {return
      $model;
    } else {
      throw new notfoundhttpexception ("Object not Found: $id");}}


View

The view action does not need to change, because model has getrelated's own mechanism

Class Viewaction extend Action
{public
  function run ($id)
  {
    $model = $this->findmodel ($id);
    if ($this->checkaccess) {
      call_user_func ($this->checkaccess, $this->id, $model);}}


Update

Public function Run ($id)
{/
  * @var $model ActiveRecord */
  $model = $this->findmodel ($id);
  if ($this->checkaccess) {
   call_user_func ($this->checkaccess, $this->id, $model);
  }
  $model->scenario = $this->scenario;
  $model->load (Yii:: $app->getrequest ()->getbodyparams (), "");
  $model->save ();
  return $model;
}

After the transformation, we need to satisfy the update action of the association model.

Public function Run ($id) {/* @var $model ActiveRecord */$model = $this->findmodel ($id);
  if ($this->checkaccess) {call_user_func ($this->checkaccess, $this->id, $model);
    } $model->scenario = $this->scenario; * * * x-www-form-urlencoded key=>value * Image mmmmmmmm * Link nnnnnnnnnn * newsitem[title]=& GT;TTTTTTTTTTT, don ' t use newsitem["title"] * newsitem[body]=>bbbbbbbbbbb * don ' t use Newsitem=>array ("Ti Tle ":" Tttttt "," Body ":" BBBBBBB ") * don ' t use newsitem=>{" title ":" Ttttttt "," Body ":" BBBBBBBB "} * * * * $ne
    Wsitem = Yii:: $app->getrequest ()->getbodyparams () [' NewsItem ']; /* Array ([title] => ttttttttttt [body] => bbbbbbbbbbb) */$model->n
    Ewsitem->load ($newsItem, ");
    # $model->newsitem->load (Yii:: $app->getrequest ()->getbodyparams (), ");
    #print_R ($model->newsitem); exit; #print_R ($model->newsitem);Exit
      if ($model->save ()) {$model->load (Yii:: $app->getrequest ()->getbodyparams (), ");
    $model->newsitem->save ();
return $model;

 }

This should also be done to NewsItem save failure, for the moment not to deal with.

For more information on YII-related content, readers who are interested in this site can view the topics: Introduction to YII Framework and summary of common skills, "Summary of PHP Excellent development framework", "Smarty Template Introductory Course", "Introduction to PHP object-oriented programming", "PHP string" Summary of Usage , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design based on the YII framework.

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.