A Simple Resource Injector for ZF Action Controllers

Matthew Weier O’Phinney writes a very use­ful arti­cle about resource injec­tion; Bran­don Sav­age approached me with an inter­est­ing issue regard­ing ZF boot­strap resources, and access­ing them in your action con­trollers. Basi­cally, he’d like to see any resource ini­tial­ized by the boot­strap imme­di­ately avail­able as sim­ply a pub­lic mem­ber of his action controller.

So, for instance, if you were using the “DB” resource in your appli­ca­tion, your con­troller could access it via $this->db.

I quickly drafted up a proof of con­cept for him using an action helper:


class My_ResourceInjector extends Zend_Controller_Action_Helper_Abstract
{
protected $_resources;

pub­lic func­tion __construct(array $resources = array())
{
$this->_resources = $resources;
}

pub­lic func­tion pre­Dis­patch()
{
$boot­strap = $this->getBootstrap();
$con­troller = $this->getActionController();
fore­ach ($this->_resources as $name) {
if ($bootstrap->hasResource($name)) {
$controller->$name = $bootstrap->getResource($name);
}
}
}

pub­lic func­tion get­Boot­strap()
{
return $this->getFrontController()->getParam(‘bootstrap’);
}
}

In this action helper, you would spec­ify the spe­cific resources you want injected via the $_resources prop­erty – which would be val­ues you pass in. Each resource name would then be checked against those avail­able in the boot­strap, and, if found, injected into the action con­troller as a prop­erty of the same name.

You would ini­tial­ize it in your bootstrap:


class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initResourceInjector()
{
Zend_Controller_Action_HelperBroker::addHelper(
new My_ResourceInjector(array(
'db',
'layout',
'navigation',
));
);
}
}

The above would map three resources: “db”, “lay­out”, and “nav­i­ga­tion”. This means you can refer to them directly as prop­er­ties in your controllers:


class FooController extends Zend_Controller_Action
{
public function barAction()
{
$this->layout->disableLayout();
$model = $this->getModel();
$model->setDbAdapter($this->db);
$this->view->assign(
'model' => $this->model,
'navigation' => $this->navigation,
);
}

// …
}

This approach leads to some nice brevity — you no longer need to fetch the boot­strap from the instan­ti­a­tion argu­ments, and then fetch the resource.

I thought about it some more, and real­ized that there’s a few prob­lems: How do you know what is being injected from within the con­troller? How do you con­trol what is being injected.

So, I revised it to pull the expected depen­den­cies from the action con­troller itself…

Read the com­plete arti­cle here A Sim­ple Resource Injec­tor for ZF Action Con­trollers.

Tags: , , , , , ,

Leave a Comment

*

Get Adobe Flash playerPlugin by wpburn.com wordpress themes