Why do classes use a helper for translation instead of $this?
Just theorizing, but when you call
$this->__('Foo')
in a template, which module's CSV translation file will Magento use to translate Foo?
It's not always clear which module's translation helper Magento will ultimately call to translate the string/key. Since Magento allows you to use the same key in different modules for different strings, it's often important to know which module's translation data you're using. In fact, if a template is used across multiple modules, using $this->__()
might be "considered harmful", as it would return different values depending on the block context the layout system used the template in.
My guess is the convenience helpers were added up front, but the developers building out the templates quickly starting instantiating helps so they knew which module's translation file would translate a string, and that pattern spread to the test of the framework. This line of code, by itself, is ambiguous.
$this->__('Foo');
But you can be sure this line of code will use the Mage_Catalog
localization information.
Mage::helper('catalog')->__('Foo')
Because you want to use an explicit module.
If you use $this->__()
in a block context, the module of the block is used for translation. So if you want to use a special module, then you have to use Mage::helper('mymodule')->__()
Basically I'm going to say the same thing as the other guys said.
If you use Mage::helper(...)
you make sure that a specific helper is used for translation.
For example let's take the Mage_Adminhtml_Block_Catalog_Product_Grid
block.
For the column headers there is this: 'header'=> Mage::helper('catalog')->__('Name'),
. if instead of the catalog helper $this->__
would have been used, the text would have been translated using the Mage_Adminhtml
module.
But this is a case where the logic behind using named helpers makes sense.
I just wanted to show a case where using $this->__('..')
instead of the helper approach can lead to problems. I speak from experience.
Let's take the block Mage_Catalog_Block_Breadcrumbs
. There is one line that looks like this: Mage::helper('catalog')->__('Home')
.
You would think that you are in the catalog
module so you could use $this
instead. But what if you override the block by your block called Namespace_Module_Block_Breadcrumbs
?
If $this
was used then the module used for translation would be Namespace_Module
and you probably don't want that.
There are two options to avoid this. Either using a named helper as it already happens for most of the core blocks.
Or you as a developer can add this in the block class:
public function getModuleName() {
return 'Mage_Catalog';
}
Then you are sure that all the texts using $this->__
from your block (templates that render the block also included) are going to be translated using the catalog module.