Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Extend Zend View to Implement a Concrete Function?

I want to make it as easy as possible for our designers to localise strings in views, which means that I want to do this:

...
<p><?php echo $this->_("Hello, world!"); ?></p>
...

The underscore notation here is necessary to allow Poedit to automagically extract all strings for localisation. The implementation is trivial:

public function _($string)
{
    return Zend_Registry::get('Zend_Translate')->_($string);
}

At the moment, I've put this directly in Zend_View_Abstract, which is bad (I don't want to do this by modifying any of the Zend library). Ideally, then, I'd extend Zend_View_Abstract to allow me to implement other concrete functions that we require, but I don't know how to set this up. An alternative might be to implement a View Helper, but the only way that I know how to do this makes the code in the view more verbose. Any pointers (no, not those kind) would be much appreciated. Thanks!

like image 595
kranzky Avatar asked Apr 29 '09 03:04

kranzky


2 Answers

Obviously ignore my paths for your own...

  1. Extend Zend_View
  2. Put your method in this extended class
  3. Instantiate the class (in your bootstrap for instance)
  4. Assign it to the ViewRenderer
  5. Pass that viewrenderer to Zend_Controller_Action_HelperBroker's addHelper method
  6. Use it in your view

In /library/MegaHAL/Zend/ create View.php:

class MegaHAL_Zend_View extends Zend_View
{
    public function _($string)
    {
    return Zend_Registry::get('translate')->_($string);
    }
}

In your bootstrap:

require_once APPLICATION_PATH.'../library/MegaHAL/Zend/View.php';

$view = new MegaHAL_Zend_View();

$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);

In your view:

<p><?php echo $this->_("Hello");?></p>

I believe that will do what you want, yes?

like image 65
rg88 Avatar answered Oct 19 '22 23:10

rg88


I think that you're looking for a way to create custom view helpers.

Example:

class My_View_Helper extends Zend_View_Helper_Abstract
{
    public function translate($string)
    {
        //...
    }
}

...

$view->setHelperPath('/path/to/helpers', 'My_View_Helper');

...

Then in your views you can use it:

echo $this->translate("Hello, World!");
like image 36
Christian C. Salvadó Avatar answered Oct 20 '22 00:10

Christian C. Salvadó