Magento: When to pass variables to a block and when not to?

风格不统一 提交于 2019-12-06 05:39:46

The "right" way in Magento might actually be closer to this:

<div id="<?php echo $this->getVar1(); ?>"><?php echo $this->getVar2(); ?></div>

Having less code can be a good thing, but only when you understand the tradeoffs. For the sake of saving two lines (or no lines if you use the above technique), you are actually losing some flexibility.

The reason that Magento relies so heavily on magic get* and set* methods is that they can be overridden in a class in a transparent way.

Let's say, for argument's sake, that down the road someone overrides your class and decides that var1 should be calculated on the fly, rather than set statically (this may not happen to you often, but Varien needed to take this into account for core classes). If you set variables manually and use them as such, this would likely require you to change several references in code. However, by using magic get* methods, calculations for attributes are much simpler:

public function getVar1() {
    $value = $this->_getData('var1');
    // perform calculations here
    return $value;
}

This formulation doesn't even block the set* equivalent of the call, nor does it require any updates to code relying on this method. So, use the magic methods when you can, as they are more idiomatic to the framework and will allow you and others the maximal possible flexibility when working with your code additions.

Hope that helps!

Thanks, Joe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!