Yii Overriding common break functions
I am new to yii2. I want to write restful api in yii framework. With 3 days of searching, I can run an example of reassuring services. I found that yii generates these methods by automatically indexing, browsing, creating, updating, deleting. What if I want to customize the indexing, create, update and delete method? Because I just found a method to customize the output of the index function, which is prepareDataProvider. And what should I do if I add a new method? Or, it is better to write your own methods if yii does not provide create, update and delete method settings.
source to share
You can always override the original behavior by specifying a method actions()
in your class ActiveController
.
Here's an example:
public function actions()
{
return array_merge(parent::actions(), [
'create' => null, // Disable create
'view' => [
'class' => 'yii\rest\ViewAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'findModel' => ['\path\to\your\callback', 'findModelByYourOwnMethod'],
],
'update' => [
'class' => 'path\to\your\UpdateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => SCENARIO_UPDATE,
],
]);
}
You can define your own action class, script, etc. If you want to override some, but not all of the actions, remember to combine with parent::actions()
.
EDIT
In general, you can always add additional actions to the controller: 1) declare a method actionX()
, where X is the name of the action; and / or 2) a declaration method actions()
that returns an array of action configuration, as in the example above. And the Yii2
framework provides a dedicated controller \yii\rest\ActiveController
that provides implemented actions for CRUD and index.
If you are reading the source code, you will notice that ActiveController
there is a method in there actions()
that has defined something similar to the example above. Each action is associated with class
under the same package, eg 'index' => ['class' => 'yii\rest\IndexAction']
. The implementation in each activity is different, and some provide an optional callable variable for the developer to set and override the original behavior. IndexAction
, for example, provides $prepareDataProvider;
for overriding; and you can see from my example, $findModel
this is another one that appears in every rest action.
I am not going to list such a callable variable here unless the community has strong needs. To understand what needs to be filled to expand the behavior of the rest of the actions, check the source code in the rest
framework folder : https://github.com/yiisoft/yii2/tree/master/framework/rest ; and FYI, I have another answer that might help you understand more: Yii2 Restful API - example of adding a new activity
source to share