17 Jan 2010
I’ve used a few different CSS/JS bundlers, but none have ever fulfilled all that I needed. Specifically, I wanted one that could do all of the following:
Thus, I created bundle-phu. Bundle-phu is a set of Zend Framework view helpers that do all of the above.
Bundle-phu is inspired by, bundle-fu a Ruby on Rails equivalent.
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/foo.js"></script>
<script type="text/javascript" src="/js/bar.js"></script>
<script type="text/javascript" src="/js/baz.js"></script>
<link media="screen" type="text/css" href="/css/jquery.css" />
<link media="screen" type="text/css" href="/css/foo.css" />
<link media="screen" type="text/css" href="/css/bar.css" />
<link media="screen" type="text/css" href="/css/baz.css" />
<script type="text/javascript" src="bundle_3f8ca8371a8203fcdd8a82.css?1234567890"></script>
<link type="text/css" src="bundle_3f8ca8371a8203fcdd8a82.css?1234567890"></script>
Place the BundlePhu directory somewhere in your include_path:
your_project/
|-- application
|-- library
| `-- BundlePhu
|-- public
Add the BundlePhu view helpers to your view’s helper path, and configure the helpers:
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initView()
{
$view = new Zend_View();
$view->addHelperPath(
PATH_PROJECT . '/library/BundlePhu/View/Helper',
'BundlePhu_View_Helper'
);
$view->getHelper('BundleScript')
->setCacheDir(PATH_PROJECT . '/data/cache/js')
->setDocRoot(PATH_PROJECT . '/public')
->setUseMinify(true)
->setMinifyCommand('java -jar yuicompressor -o :filename')
->setUseGzip(true)
->setGzipLevel(9)
->setUrlPrefix('/javascripts');
$view->getHelper('BundleLink')
->setCacheDir(PATH_PROJECT . '/data/cache/css')
->setDocRoot(PATH_PROJECT . '/public')
->setUrlPrefix('/stylesheets');
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
$viewRenderer->setView($view);
return $view;
}
}
As both these helpers extend from the existing HeadScript and HeadLink helpers in Zend Framework, you can use them just as you do those.
<? $this->bundleScript()->offsetSetFile(00, $this->baseUrl('/js/jquery.js')) ?>
<? $this->bundleScript()->appendFile($this->baseUrl('/js/foo.js')) ?>