如何在Yii2 restful controller中执行其他任务?

Vik*_*293 5 php api rest yii-components yii2

这是我的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
    }

  }
Run Code Online (Sandbox Code Playgroud)

它在默认行为下运行良好,但您只是创建用户并退出是不太实际的.您需要发送带有验证链接短信等的电子邮件,可能会根据此操作更新其他一些模型.

我不想完全覆盖create方法,因为它可以很好地保存数据并返回JSON.我只是想通过添加一个函数的回调类来扩展它的功能,该函数可以接受新创建的用户并向该人发送电子邮件.

Ali*_*our 2

afterSave()最简单的方法是从模型中的方法中获益。每次保存过程后都会调用此方法。

public function afterSave($insert, $changedAttributes) {
    //calling a send mail function
    return parent::afterSave($insert, $changedAttributes);
}
Run Code Online (Sandbox Code Playgroud)

此方法的另一个优点是您存储在对象模型中的数据。例如访问email字段:

 public function afterSave($insert, $changedAttributes) {
    //calling a send mail function
    \app\helpers\EmailHelper::send($this->email);
    return parent::afterSave($insert, $changedAttributes);
}
Run Code Online (Sandbox Code Playgroud)

的值$this->email包含保存到数据库中的值。

注意 您可以受益于$this->isNewRecord检测模型是否将新记录保存到数据库中或更新现有记录。看一看:

public function afterSave($insert, $changedAttributes) {
    if($this->isNewRecord){
        //calling a send mail function
        \app\helpers\EmailHelper::send(**$this->email**);
    }
    return parent::afterSave($insert, $changedAttributes);
}
Run Code Online (Sandbox Code Playgroud)

现在,只有在将新记录保存到数据库中时,它才会发送邮件。

请注意,您还可以从 Yii2 的EVENTS.

正如 Yii2 的官方文档

该方法在插入或更新记录结束时调用。默认实现将EVENT_AFTER_INSERT在 $insert 为 true 时触发事件,或者EVENT_AFTER_UPDATE在 $insert 为 false 时触发事件。使用的事件类是yii\db\AfterSaveEvent. 重写此方法时,请确保调用父实现以便触发事件。