PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Resource Plugins

As noted previously, a good way to create re-usable bootstrap resources and to offload much of your coding to discrete classes is to utilize resource plugins. While Zend Framework ships with a number of standard resource plugins, the intention is that developers should write their own to encapsulate their own initialization needs.

Resource plugins need only implement Zend_Application_Resource_Resource, or, more simply still, extend Zend_Application_Resource_ResourceAbstract. The basic interface is simply this:

<?php
interface Zend_Application_Resource_Resource
{
    public function 
__construct($options null);
    public function 
setBootstrap(
        
Zend_Application_Bootstrap_Bootstrapper $bootstrap
    
);
    public function 
getBootstrap();
    public function 
setOptions(array $options);
    public function 
getOptions();
    public function 
init();
}

The interface defines simply that a resource plugin should accept options to the constructor, have mechanisms for setting and retrieving options, have mechanisms for setting and retrieving the bootstrap object, and an initialization method.

As an example, let's assume you have a common view intialization you use in your applications. You have a common doctype, CSS and JavaScript, and you want to be able to pass in a base document title via configuration. Such a resource plugin might look like this:

<?php
class My_Resource_View extends Zend_Application_Resource_ResourceAbstract
{
    protected 
$_view;

    public function 
init()
    {
        
// Return view so bootstrap will store it in the registry
        
return $this->getView();
    }

    public function 
getView()
    {
        if (
null === $this->_view) {
            
$options $this->getOptions();
            
$title   '';
            if (
array_key_exists('title'$options)) {
                
$title $options['title'];
                unset(
$options['title']);
            }

            
$view = new Zend_View($options);
            
$view->doctype('XHTML1_STRICT');
            
$view->headTitle($title);
            
$view->headLink()->appendStylesheet('/css/site.css');
            
$view->headScript()->appendfile('/js/analytics.js');

            
$viewRenderer =
                
Zend_Controller_Action_HelperBroker::getStaticHelper(
                    
'ViewRenderer'
                
);
            
$viewRenderer->setView($view);

            
$this->_view $view;
        }
        return 
$this->_view;
    }
}

As long as you register the prefix path for this resource plugin, you can then use it in your application. Even better, because it uses the plugin loader, you are effectively overriding the shipped "View" resource plugin, ensuring that your own is used instead.

Zend Framework