Tuesday, February 15, 2011

Keeping Zend View Helpers organized

Over the last couple years I have accumulated a pretty large closet full of view helpers. Some of them are specific to certain projects, but many of them (my favorites) are much more flexible and still very useful

I have almost as many ways to organize them as I do helpers. They are all more or less the same idea (similar helpers grouped in folders) but have some fundamental differences depending on the way I structured my apps.

I ultimately resorted to a system where each module (in Digitalus Framework) has its own view helper dir, as the standard describes, and then I added a naming convention where the function name had the module name prepended. This works well and is similar to the way ZF does other things, but leaves something to be desired.

At the core we are all professional typists. The more words you type the more work you get done. So the fastest typist (all other things equal) is the best programmer. This oversimplification is probably true, unless you actively strive to minimize the amount that you have to type. 

The solution I am using right now is a (very simple) view helper which helps me load the helper packages that I need, so I can eliminate the extraneous prefixes and what not. I also think it makes the code much easier to follow.


<?php
/**
 * this helper makes it easier to include the core view helper packages of the dig library
 *
 */
class Dig_View_Helper_Using extends Zend_View_Helper_Abstract {
    public function using($package) {
        $package = ucfirst($package);
        $baseHelperPath = realpath(dirname(__FILE__));
        $packagePath = $baseHelperPath . '/' . $package;
        $this->view->addHelperPath($packagePath, 'Dig_View_Helper_' . $package);
    }
}

Then I load the necessary view helpers in the head of the view script:

<?php
$this->using('content');
?>

And then get to use nice short function names for the helpers:

<?= $this->textile($instructions);?>

No comments:

Post a Comment