简体   繁体   中英

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

I have recently found the power of setting variables to a block in the _toHtml() method, using the assign method. My question is, when is it good to do this and when is it not? I am creating a new module and it seems to me it is much nice to just assign all the variables to the block and just reference those variables in the view file rather then setting up something like this

<?php
  $var1 = $this->getVar1();
  $var2 = $this->getVar2();
?>

<div id="<?php echo $var1 ?>"><?php echo $var2 ?></div>

Isn't better to just set those in the block class and just call the variables in the phtml file? Then your template file would just look like

<div id="<?php echo $var1 ?>"><?php echo $var2 ?></div>

This would remove more php code being in the template, which I think is good?

The only thing I can think of is, it will be harder to know what variables are set when other developers are working on the template file. If I put a comment at the top that all variables are mostly set in x block class that would help or if they are debugging they will see all the variables set but I guess it could still be confusing, and I am assuming this is why Magento has only did it sparingly.

But I am looking for anyone else's opinion on this for best practices.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM