在 OO 环境(Zend Framework)中使用全局函数进行翻译
我正在开发一个基于 Zend Framework 的项目。我正在使用 Zend_Translate 进行翻译,但我希望尽可能减少应用程序(视图)前面的额外代码量。文本的翻译应该如下所示:
echo __("Text to translate");
使用视图助手并不能做到这一点,因为然后我得到:
echo $this->__("Text to translate");
这意味着我必须在某处声明一个全局函数,它调用 Zend_Translate 来完成其余的工作。因为我希望项目尽可能保持干净,所以我想要一些关于在哪里放置此函数的建议。
我考虑过在引导程序中的 _initLocale() 内部包含一个带有全局函数的文件。
基本上我的问题是:我现在是否违反了所有神圣的 MVC 原则,或者这是正确的方法吗?
I am working on a project build on the Zend Framework. I'm using Zend_Translate to do my translations, but I want to keep the amount of extra code in the front of my application (views) as minimal as possible. Translation of a text should look like this:
echo __("Text to translate");
Using a view helper isn't doing it, because then I get:
echo $this->__("Text to translate");
This would mean I have to declare a global function somewhere, that calls for Zend_Translate to do the rest of the magic. Because I want the project to stay as clean as possible I'd like some suggestions on where to put this function.
I have considered including a file with my global function inside of the _initLocale() in the bootstrap.
Basically my question is: am I now violating all the holy MVC principles, or is this the right way to go?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这其实不是一个容易回答的问题。当然,您违反了 OOP 的一些原则,因为您基本上是用数百个小整体来标记您的对象,而实际上应该只有一个。您应该将翻译对象注入到控制器和视图中一次,然后调用
$this->__()
。通过在Zend_Controller_Action
和您自己的控制器之间创建一个中间层也可以轻松完成此操作。但是...翻译是一个非常具体的案例,我认为您的解决方案不会带来太多潜在的危害。 Translation 方法不太可能改变其逻辑,如果您需要重命名它,查找并替换后跟括号的两个下划线很可能不会产生除翻译后的字符串之外的任何内容...然后再次使用“最有可能”是已经有气味了。总结:看起来或多或少还可以,但我仍然不会这样做,特别是如果它是一个具有某种意义且预期寿命长达几年的软件。
This is actually not an easy question to answer. Of course you're violating some principles of OOP because you're basically punctuating your objects with hundreds of little wholes where there should be just one. You should be injecting the translation object into your controllers and views once and then call
$this->__()
. This is also easily done by creating an intermediate layer betweenZend_Controller_Action
and your own controllers. BUT... translation is a very specific case and I don't see much potential harm coming from your solution. The Translation method is not likely to change its logics and if you need to rename it, finding and replacing two underscores followed by a bracket will most probably not yield anything else than translated strings... then again that use of 'most probably' is a smell already.Summary: It seems more or less ok but I still wouldn't do it, especially if it's a software of some meaning with an expected life span of some years.