如何在zend框架视图中使用$ this-> _()? [英] How to use $this->_() in zend framework views?
问题描述
在我的ZF 1.11应用程序中,我将翻译器存储在注册表中,如下所示:
In my ZF 1.11 application I'm storing my translator in registry like this:
Zend_Registry::set('Zend_Translate', $translator);
因此,在我的视图脚本中,我可以通过以下方式访问翻译器:
So in my view scripts I can access the translator this way:
$this->translate('abc');
有什么聪明的方法可以代替使用此呼叫:
Is there any clever way to be able to use this call instead:
$this->_('abc');
使用$ this-> translate使视图混乱,很多人还是习惯于看到_().
Using $this->translate clutters the views, and lot's of people are used to seeing _() anyway.
推荐答案
我通常同意函数/方法名称应该有意义的概念,但我也同意翻译的_()
是广泛使用的标准,因此可以接受.
Whereas I generally agree with the notion that function/method names should be meaningful, I also agree that the _()
for translations is a widely used standard and therefore acceptable.
您可以通过在中间层添加包装器来实现.例如,以下内容将使该方法可用于所有从MyProject_Controller_Action
派生的控制器:
You can do this by adding wrappers to your intermediate layers. For example the following would make the method available to all your controllers derived from MyProject_Controller_Action
:
class MyProject_Controller_Action extends Zend_Controller_Action
{
protected $translator;
public function init()
{
$this->translator = Zend_Registry::get('Zend_Translate');
}
/**
* Translator wrapper
*
* @param string $string The string to be translated
* @return string $translated The translated string
*/
protected function _($string)
{
$translated = $this->translator->translate($string);
return $translated;
}
}
当然可以使用Zend_View
进行同样的操作.
Of course the same can be done with Zend_View
.
免责声明:最好的做法是直接调用注册表来使代码混乱.实际上,这是一种反模式,应由DI代替. Zend Framework 2
将使我们更容易避免注册表.可以通过实际上通过构造函数将翻译对象注入到类中来改进此代码.
Disclaimer: It is not the best practice to clutter your code with direct calls to the registry. Actually it's an anti-pattern which should be replaced by DI. Zend Framework 2
will make it much easier for us to avoid the registry. This code could be improved by actually injecting the translation object into the class via constructor.
这篇关于如何在zend框架视图中使用$ this-> _()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!