Let’s work together

Feel free to send me an email at [email protected]

Research Campus 18
3500 Hasselt
Belgium

Minifying your Zend Framework views


Minifying your Zend Framework views

When your website is getting alot of traffic, you’ll eventually reach the point where you want to tune things (or good habits). Next to backend and frontend caching, checking your expiry headers, optimizing images, … you can also minify your application’s output. Minifying or ‘minification’ is ‘the process of removing all unnecessary characters from source code, without changing its functionality‘.

Now keep in mind, it’s always better to load your CSS from an external stylesheet, this way it can get cached + you can use a very cool tool called http://code.google.com/p/minify/ . This leaves us with all the other code, your website’s HTML.

Using view output filters in Zend, it’s fairly easy to minify all your html/javascript/css output. In this blog post I’ll show you how to get things up and running. We’ll be using the same open source Minify library (http://code.google.com/p/minify/source/browse/#svn%2Ftrunk%2Fmin%2Flib)

Create a new view output helper (more about this):

<!--?php
require_once 'Zend/Filter/Interface.php';
require_once 'Minify/HTML.php';
require_once 'Minify/CSS.php';
require_once 'JSMin.php';
 
class My_View_Filter_Minify implements Zend_Filter_Interface
{
    public function filter($value) 
    {
    	return Minify_HTML::minify($value, array(
    	    'cssMinifier' =--> array('Minify_CSS', 'minify'),
            'jsMinifier' =&gt; array('JSMin', 'minify')
    	));
    }
}

Next and final step is letting our project know we want to use this new filter globally, so add the following code in your bootstrap:

public function _initMinifyHTML()
{
    $this-&gt;bootstrap('view');
    $view = $this-&gt;getResource('view');
    $view-&gt;addFilterPath('My/View/Filter', 'My_View_Filter');
    $view-&gt;setFilter('Minify');		
}