Pergunta

I'm currently using Zend Framework 2 beta for on PHP 5.4.4 to develop a personal webapp for self-study purpose.

I was wondering if it is possible to intercept the html output just before it is sent to the browser in order to minify it by removing all unnecessary white spaces.

How could I achieve this result in ZF2?

Foi útil?

Solução

Yep, you can:

On Modle.php create an event that will trigger on finish

public function onBootstrap(Event $e)
{
    $app = $e->getTarget();
    $app->getEventManager()->attach('finish', array($this, 'doSomething'), 100);
}


public function doSomething ($e)
{
    $response = $e->getResponse();
    $content = $response->getBody();
    // do stuff here
    $response->setContent($content);

}

Outras dicas

Just put this two method inside any module.php . It will gzip and send compressed out put to the browser.

 public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    $eventManager->attach("finish", array($this, "compressOutput"), 100);
}

public function compressOutput($e)
    {
        $response = $e->getResponse();
        $content = $response->getBody();
        $content = preg_replace(array('/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', '#(?://)?<![CDATA[(.*?)(?://)?]]>#s'), array('>', '<', '\\1', "//&lt;![CDATA[n" . '1' . "n//]]>"), $content);

        if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
            header('Content-Encoding: gzip');
            $content = gzencode($content, 9);
        }

        $response->setContent($content);
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top