An object assigning action helper

by Naneau

I’m sorry for the cryptic title, but I’ll explain it. One of the major challenges in software design nowadays is portability. It’s one of the cornerstones of object oriented programming. The basic idea being that if you define a class that describes some kind of thing, in any other applications that work with the same kind of thing, you can re-use the class.

Controllers are no different. I have mentioned this on my blog before, but it keeps popping up. If you plan on writing modules for an application, it pays to design them in such a way that they can be re-used in another project. Of course, some projects have specialized business logic that you will never need again. But if you have a look at totally different websites, some elements keep reoccurring. Things like contact forms, news sections, sitemaps, etc.

Eric Coleman, who hangs out a lot on #zftalk and I were having a chat about being lazy. It started when he said that having to type $this->_helper-> can be a bit cumbersome. Good programmers are lazy of course. I created a small action helper to assign all available helpers to the controller.

While doing so I found that Zend_Controller_Action_HelperBroker lacks a method to return all registered helpers. Apart from that writing it took me 5 minutes. Eric suggested to add a manual assign method to it as well, which was really a great idea. He did do a bad job on trying to implement it himself though, but I forgive him ;)

The benefit of having a manual assign method is that you can assign things you need in your controllers from outside controller context. You no longer need a subclassed controller, an init() method, or the Zend_Registry. For things like a database connection this can be handy, you can just use $this->_db from controller context, after altering your bootstrap, adding just three lines:

1
2
3
4
5
6
7
8
$assign = new Naneau_Action_Helper_Assign();
//assign action helper
Zend_Controller_Action_HelperBroker::addHelper($assign);
//add the helper to the helper broker

//create $db
$assign->assign('db', $db);
//make the db available to controllers as $this->_db

Too bad it relies on a patched Zend_Controller_Action_HelperBroker, but otherwise I’d release it. If you are interested in it’s inner workings, I suggest you check out this paste on pastebin.ca. You can expect a follow up on this.

Update

The Zend_Controller_Action_HelperBroker has been fixed in newer versions of the framework. So this helper now works out of the box :)