Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable gzip compression in Yii2

Tags:

php

gzip

yii2

How to enable gzip compression in Yii2?

I have tried to use the code below in web/index.php but it returns empty

$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();
like image 382
Harris Avatar asked Jul 20 '15 12:07

Harris


2 Answers

Not sure if this is the best practice, but I made it work by attaching event handler on 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();
like image 123
Harris Avatar answered Oct 08 '22 18:10

Harris


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();
    }
);
like image 41
ingenious Avatar answered Oct 08 '22 20:10

ingenious