Analysis of Restful API principles in Yii2, yii2restful
This article analyzes the Restful API principle in yii2. We will share this with you for your reference. The details are as follows:
Yii2 has a very important feature of default support for Restful APIs. With just a few configurations, You can implement simple RESTful APIs for existing models.
Here, by analyzing the rest source code, we will briefly analyze the principle of yii2 implementing restful, and use some customization to implement RESTful api operations on the associated model.
~ Represents the relationship between 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 of the RESTful API Controller class.
In the control cycle of an API request, it implements the following steps 1 ~ 5:
① Parse the response content format
② Verification Request Method
③ Test User Permissions
④ Speed Limit
⑤ Format the 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 (see [[ContentNegotiator]]); * 2. Validating request method (see [[verbs()]]). * 3. Authenticating user (see [[\yii\filters\auth\AuthInterface]]); * 4. Rate limiting (see [[RateLimiter]]); * 5. Formatting response data (see [[serializeData()]])behaviors contentNegotiator verbFilter authenticator rateLimiterafterAction serializeData Yii::createObject($this->serializer)->serialize($data)verbs []*/class Controller extends \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' => VerbFilter::className(), 'actions' => $this->verbs(), ], 'authenticator' => [ 'class' => CompositeAuth::className(), ], 'rateLimiter' => [ 'class' => RateLimiter::className(), ], ] } public function verbs() { return []; } public function serializeData($data) { return Yii::createObject($this->serializer)->serialize($data); } 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 interworking data with ActiveRecord.
The Class Name of ActiveRecord is specified 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 override actions () and unsetting the response action to disable these default actions.
Add a new action to overwrite actions () and add a new action class or a new action method to its end.
Note that you also overwrite the verbs () Method to declare this new action to support those HTTP methods.
You also need to overwrite checkAccess () to check whether the current user has the permission to perform a response action.
Write the Controller again according to the preceding instructions.
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('The "modelClass" property must be set.'); } } public function actions() { return [ 'index' => [ 'class' => 'app\controllers\rest\IndexAction', '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 = []) { }}
The following is a News controller inherited from the rest \ ActiveController:
Namespace app \ controllers; use app \ controllers \ rest \ ActiveController; # the AC, I copied a copy from yii/rest of the class NewsController extends ActiveController {public $ modelClass = 'app \ models \ News ';}
Defining this is enough to implement the default method in rest \ ActiveController.
Below are some customized methods.
Class NewsController extends ActiveController {public $ modelClass = 'app \ models \ News'; # custom serializer # public $ serializer = 'yii \ rest \ Serializer '; public $ serializer = ['class' => 'app \ controllers \ rest \ Serializer ', 'collectionenvelope' => 'items ',]; public function behaviors () {$ be = ArrayHelper: merge (parent: behaviors (), ['verbfilter' => ['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 major changes to Actions, we recommend that you copy them out. Do not use the original yii \ rest \ XXXAction namespace.
Here, I want to implement the CURD operation on the related models as a major change.
Action
Before customizing each action, let's take a look at their base class rest \ Action, which is mainly 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::primaryKey(); 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 be modified because the model has its own getRelated 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 transformation, the update action for the associated model must be met.
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]=>ttttttttttt , don't use newsItem["title"] * newsItem[body]=>bbbbbbbbbbb * don't use newsItem=>array("title":"tttttt","body":"bbbbbbb") * don't use newsItem=>{"title":"ttttttt","body":"bbbbbbbb"} * */ $newsItem = Yii::$app->getRequest()->getBodyParams()['newsItem']; /* Array ( [title] => ttttttttttt [body] => bbbbbbbbbbb ) */ $model->newsItem->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;}
The newsItem save failure should also be processed here.