如何在Yii2中启用gzip压缩

时间:2015-07-20 12:05:57

标签: php gzip yii2

如何在Yii2中启用gzip压缩?

我尝试在web / index.php中使用下面的代码,但它返回空

$application = new yii\web\Application($config);
$application->on(yii\web\Application::EVENT_BEFORE_REQUEST, function($event){
    ob_start("ob_gzhandler");
});
$application->on(yii\web\Application::EVENT_AFTER_REQUEST, function($event){
    ob_end_flush();
});
$application->run();

2 个答案:

答案 0 :(得分:4)

不确定这是否是最佳做法,但我通过在yii \ web \ Response上附加事件处理程序使其工作

$application = new yii\web\Application($config);
$application->on(yii\web\Application::EVENT_BEFORE_REQUEST, function(yii\base\Event $event){
    $event->sender->response->on(yii\web\Response::EVENT_BEFORE_SEND, function($e){
        ob_start("ob_gzhandler");
    });
    $event->sender->response->on(yii\web\Response::EVENT_AFTER_SEND, function($e){
        ob_end_flush();
    });
});
$application->run();

答案 1 :(得分:2)

更好的想法是,你可以在任何地方使用它(比如控制器或动作):

\yii\base\Event::on(
    \yii\web\Response::className(), 
    \yii\web\Response::EVENT_BEFORE_SEND, 
    function ($event) {
        ob_start("ob_gzhandler");
    }
);

\yii\base\Event::on(
    \yii\web\Response::className(), 
    \yii\web\Response::EVENT_AFTER_SEND, 
    function ($event) {
        ob_end_flush();
    }
);