php – 使用Yii 2.0加密REST响应流

我想加密REST-Request的响应流.我从数据库中获取数据并将其作为xml(actionAll)返回.这很好用.然后我添加了一个在响应发送到客户端之前执行的eventHandler(beforeAction).这也有效.我的问题是,当eventHandler调用它时,encryptResponse方法中的$response不包含任何数据.变量content,data和stream在response-object中始终为null.

谢谢你的帮助!

<?php

namespace app\controllers;

use Yii;
use app\models\Order;
use yii\filters\auth\HttpBasicAuth;
use yii\web\Response;
use app\models\User;

class OrderController extends \yii\rest\Controller{

    /**
    * disable session for REST-Request
    * no loginUrl required  
    */
     public function init(){
        parent::init();
        \Yii::$app->user->enableSession = false;
        \Yii::$app->user->loginUrl = null;
    }

   /**
    * HttpBasicAuth for authentication  
    */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
        'class' => HttpBasicAuth::className(),
        'auth'  => function ($username, $password) {
            if($username==\Yii::$app->params['HttpBasicAuth']['username'] &&     $password==\Yii::$app->params['HttpBasicAuth']['password']){
                return new User();
            }else{
                return null;
            }
        }];
        return $behaviors;
    }

   /**
    * set response-format to xml
    * fetch data from db
    *   
    */
    public function actionAll(){
        \Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
        $models = Order::find()->all(); 
        return $models;
    }

   /**
    * hook into action and add event handler    
    */
    public function beforeAction($action){      
        $response = Yii::$app->getResponse();
        $response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);
    }

   /**
    * callback for event-handler    
    */
    public function encryptResponse(){
        $response = Yii::$app->getResponse();
        var_dump($response);
    }   
}

最佳答案 您可以在init中设置响应事件.

或者您只需要在beforeAction函数中添加return true,否则数据将为null,因为未调用该操作,这在Yii2 docs here中也有提及.

use Yii;

...

public function init() 
{
    parent::init();

    Yii::$app->user->enableSession = false;
    Yii::$app->user->loginUrl = null;
    Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);
}

public function beforeAction($action)
{      
    $response = Yii::$app->getResponse();
    $response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);

    return true; // << required
}
点赞