這是我的RESTful控制器的樣子。如何在Yii2寧靜控制器中執行其他任務?
<?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(){
\t //Need to call this function on every create
\t //This should also have the information about the newly created user
}
}
它的工作原理非常好,默認的行爲,但它是不是很實用,你將只需要創建用戶並退出。你需要發送電子郵件與驗證鏈接短信等,可能會更新一些其他模式的基礎上,這一行動。
我不想完全重寫create方法,因爲它很好地保存數據並返回JSON。 我只想通過添加一個函數的回調類來擴展它的功能,該函數可以接受新創建的用戶併發送電子郵件給該人。
我已經在我的代碼中添加了這個函數,但它沒有被調用,我將不得不寫一些東西來覆蓋它嗎? – Viky293
@ Viky293這是你的'Model'類中的一個方法。我的意思是:'後端\模型\用戶'。您必須在'backend \ models \ User'類中覆蓋它。 –
感謝您的幫助,但我不希望將代碼發送到模型內部。我用afterAction()函數嘗試過,就像你已經解釋的那樣,但是我也沒有找到一個好的解決方案,因爲afterAction將在所有控制器動作之後被調用。 – Viky293