PHP, MySQL, JavaScript, Windows 7, Linux
Simple handling of jQuery dependencies with Zend Framework 1.9.x
I have a lot of experience with WordPress development, and I’ve grown to love the way JavaScript dependencies are handled in that particular application. In WordPress, all JavaScript dependencies are defined in /wp-includes/script-loader.php. To ensure jQuery loads before any jQuery-dependent scripts, you just use $script->add() and reference the jQuery library ID. Easy as pie.
Zend Framework’s ZendX JQuery extension has similar functionality, though what I will discuss below is not as advanced as the WP library. To achieve a simple version of this functionality, we need to edit three files.
Step 1: Create the Helper
/**
* jQueryGlobal Helper file
*
* @file /application/views/helpers/jQueryGlobal.php
*/
class Zend_View_Helper_jQueryGlobal extends Zend_View_Helper_Abstract {
public function jQueryGlobal() {
$jquery = $this->view->jQuery();
// Enable jQuery
$jquery->enable();
// Set jQuery version to latest stable release
$jquery->setVersion('1.3.2');
$jquery->setUiVersion('1.7.2');
// Ensure site.js is loaded *after* jQuery
$jquery->addJavascriptFile('/js/site.js');
return '';
}
}
Step 2: Edit Bootstrap.php
/**
* Bootstrap file
*
* @file /application/Bootstrap.php
*/
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
protected function _initAutoload() {
$moduleLoader = new Zend_Application_Module_Autoloader( array(
'namespace' => '',
'basePath' => APPLICATION_PATH ));
return $moduleLoader;
}
protected function _initViewHelpers() {
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$view->doctype('XHTML1_STRICT');
$view->headTitle('jQuery Dependencies Example')->setSeparator(' :: ');
// Ensure all modules can use helpers
$view->addHelperPath(APPLICATION_PATH . '/views/helpers');
$view->addHelperPath('ZendX/JQuery/View/Helper', 'ZendX_JQuery_View_Helper');
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
}
}
Step 3: Edit the layout or view file(s)
<?php echo $this->doctype(); ?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <?php echo $this->headMeta(); ?> <?php echo $this->headTitle(); ?> <?php echo $this->jQueryGlobal(); ?> <?php echo $this->jQuery(); ?> </head> <body></body> </html>
That’s it! I plan on extending this to be able to handle dependencies for any JavaScript library. If anyone has experience doing this, knows of a better way, or has a simple suggestion, please by all means share it with us. We are all here to learn!
July 17, 2010 - 10:56 am
And how do you use the jQuery after setting up this?. Pure jQuery by hand or?