简体   繁体   English

如何在Yii2中启用gzip压缩

[英]How to enable gzip compression in Yii2

How to enable gzip compression in Yii2? 如何在Yii2中启用gzip压缩?

I have tried to use the code below in web/index.php but it returns empty 我试图在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();

Not sure if this is the best practice, but I made it work by attaching event handler on yii\\web\\Response 不确定这是否是最佳实践,但我通过在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();

It is better idea, you can use it anywhere(like in a controller or action): 更好的想法是,你可以在任何地方使用它(比如控制器或动作):

\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();
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM