你可以嘗試在kernel.response
事件手動gzip壓縮內容:
namespace AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class CompressionListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
KernelEvents::RESPONSE => array(array('onKernelResponse', -256))
);
}
public function onKernelResponse($event)
{
//return;
if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
return;
}
$request = $event->getRequest();
$response = $event->getResponse();
$encodings = $request->getEncodings();
if (in_array('gzip', $encodings) && function_exists('gzencode')) {
$content = gzencode($response->getContent());
$response->setContent($content);
$response->headers->set('Content-encoding', 'gzip');
} elseif (in_array('deflate', $encodings) && function_exists('gzdeflate')) {
$content = gzdeflate($response->getContent());
$response->setContent($content);
$response->headers->set('Content-encoding', 'deflate');
}
}
}
而且在配置寄存器這個監聽器:
app.listener.compression:
class: AppBundle\EventListener\CompressionListener
arguments:
tags:
- { name: kernel.event_subscriber }
非常感謝你,這聽起來非常有前途的!與'mod_deflate'壓縮相比,是否有任何性能下降?當然,使用'Apache'或'Symfony'執行'gzip'沒有什麼區別,但是緩存怎麼辦? –
我不能說性能。嘗試對apache gzip和自定義gzip進行測試。你可以通過apache'ab'程序來完成。我認爲瀏覽器緩存對兩個版本的作用都是一樣的。 –