Managing CSS and JavaScript files within a Zend Framework App - A Different Approach - View Plugin

Fri, Feb 5, 2010 2-minute read

Reading this article on the Zend Framework Blog Managing CSS and JavaScript files within a Zend Framework App, speaking personally as a front-end developer I would use a different system.

In my approach loading up different CSS/JS files per controller is the exception not the rule. We load additional CSS/JS when we need to do something very special, for example a page with a flash file uploader.

I also think loading dependent files outside of the controller can make it difficult for other developers to work on your code. You can’t just look at the controller to see what other CSS/JS dependencies are being used, you need to check the file system.

My approach is a View Plugin that manages a standard set of CSS/JS for every layout. Additional CSS/JS if needed are added in the controllers.

Onto the code!

View Plugin Example

Here is my example view plugin from a recent project:

class Plugin_View extends Zend_Controller_Plugin_Abstract {
    public function routeStartup() {

        $view = new Zend_View();

        $view->headTitle()->setSeparator(' - ')->append('');
        $view->headMeta()->appendHttpEquiv('Content-Type','text/html; charset=utf-8');

        $view->addHelperPath('ZendX/JQuery/View/Helper/', 'ZendX_JQuery_View_Helper');


        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();

The code in an example layout file:


<?= $this->doctype() ?>
<html lang="en" xml:lang="en" xmlns="">
  <?= $this->headMeta() ?>
  <?= $this->headLink() ?>
  <?= $this->jQuery() ?>        
  <?= $this->headScript() ?>
  <?= $this->headTitle()?>

As you can see from the above code, the Plugin handles everything needed for the HEAD area of the page, and it is all in one place.

Adding Additional CSS/JS From A Controller

If you need to add additional CSS/JS files, you can now do this in the controller - when needed. In the following example I need to add the dependencies for “Uploadify” a flash based multifile uploader.


class UploadController extends Zend_Controller_Action {

    public function init() {    


    public function indexAction() {

The above inserts the dependencies into the layout for this controller action only. Sweet!!

From my perspective this approach works better and I think from a code organization structure it is cleaner. Any special CSS/JS can be added on a per-controller or per-controller-action basis and it will be very clear to other developers what is being loaded and where.