Welcome to 3DMICK
info@3dmick.com
+91 (971) 119-1127

Zf Writing Custom Helpers

1h

Zf Writing Custom Helpers

The class name must, at the very minimum, end with the helper name itself, using MixedCaps. E.g., if you were writing a helper called “Testhelper”, the class name would minimally need to be “Testhelper”. We should give the class name a prefix, and it is recommended that you use ‘View_Helper’ as part of that prefix: “My_View_Helper_Testhelper”. (Now you will need to pass in the prefix, with or without the trailing underscore, to addHelperPath() or setHelperPath()).

  • The class must have a public method that matches the helper name; this is the method that will be called when your template calls “$this->testhelper()”. In our “testhelper” helper example, the required method declaration would be “public function testhelper()”.
  • In general, the class should not echo or print or otherwise generate output. Instead, it should return values to be printed or echoed. The returned values should be escaped appropriately.
  • The class must be in a file named after the helper class. Again using our “testhelper” helper example, the file has to be named “testhelper.php”.

Place the helper class file somewhere in your helper path stack, and Zend_View will automatically load, instantiate, persist, and execute it for you.

Here is an example of our SpecialPurpose helper code:

class My_View_Helper_SpecialPurpose extends Zend_View_Helper_Abstract
{
protected $_count = 0;
public function Testhelper()
{
$this->_count++;
$output = "I have seen 'The Jerk' {$this->_count} time(s).";
return htmlspecialchars($output);
}
}

Then in a view script, you can call the SpecialPurpose helper as many times as you like; it will be instantiated once, and then it persists for the life of that Zend_View instance.

// remember, in a view script, $this refers to the Zend_View instance.

echo $this->specialPurpose();
echo $this->specialPurpose();
echo $this->specialPurpose();

The output would look something like this:

I have seen 'The Jerk' 1 time(s).
I have seen 'The Jerk' 2 time(s).
I have seen 'The Jerk' 3 time(s).

Sometimes you will need access to the calling Zend_View object — for instance, if you need to use the registered encoding, or want to render another view script as part of your helper. To get access to the view object, your helper class should have a setView($view) method, like the following:

class My_View_Helper_ScriptPath
{
public $view;
public function setView(Zend_View_Interface $view)
{
$this->view = $view;
}
public function scriptPath($script)
{
return $this->view->getScriptPath($script);
}
}

If your helper class has a setView() method, it will be called when the helper class is first instantiated, and passed the current view object. It is up to you to persist the object in your class, as well as determine how it should be accessed.

If you are extending Zend_View_Helper_Abstract, you do not need to define this method, as it is defined for you.