php – 如何在Yii2 restful controller中执行其他任务?
作者:互联网
这是我的RESTful控制器的样子.
<?php
namespace backend\controllers;
use yii\rest\Controller;
use yii;
use yii\web\Response;
use yii\helpers\ArrayHelper;
class UserController extends \yii\rest\ActiveController
{
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['view', 'index'], // in a controller
// if in a module, use the following IDs for user actions
// 'only' => ['user/view', 'user/index']
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
'languages' => [
'en',
'de',
],
],
[
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 86400,
],
],
]);
}
public $modelClass = 'backend\models\User';
public function actions()
{
}
public function sendMail(){
//Need to call this function on every create
//This should also have the information about the newly created user
}
}
它在默认行为下运行良好,但您只是创建用户并退出是不太实际的.您需要发送带有验证链接短信等的电子邮件,可能会根据此操作更新其他一些模型.
我不想完全覆盖create方法,因为它可以很好地保存数据并返回JSON.
我只是想通过添加一个函数的回调类来扩展它的功能,该函数可以接受新创建的用户并向该人发送电子邮件.
解决方法:
正如您所看到的,这是使用prepareDataProvider来更改索引操作正常使用的正常方式.这非常方便.你可以在这里找到prepareDataProvider的定义:http://www.yiiframework.com/doc-2.0/yii-rest-indexaction.html#prepareDataProvider()-detail
现在您可以看到,在Run()和beforeRun()之后还有2个其他方法也可用于创建操作. http://www.yiiframework.com/doc-2.0/yii-rest-createaction.html
您可以使用这两个函数并声明它们类似于prepareDataProvider来执行更多内容,例如发送电子邮件.我自己没试过,但我相信这应该是要走的路.
标签:php,rest,yii2,api,yii-components 来源: https://codeday.me/bug/20190519/1136499.html