What’s the best way to create a temporary variable inside a .phtml template while abiding by Magento’s architecture?
Example
File: /template/catalog/product/view.phtml
<?php
$myVar = $_product->getAttributeText('color');
if ( empty($myVar) ) {
// does not exist
} else {
// show the attribute
}
?>
Beyond this expression $myVar isn’t needed anywhere else.
Note: I’m not looking for alternative ways to write this code that avoid creating vars. For the sake of argument, assume a scenario where creating a temporary var is necessary.
What should $myVar be?
- $myVar
- $namespaced_myVar
- $_myVar
- Magento’s registry pattern http://alanstorm.com/magento_registry_singleton_tutorial
- Something else…
Looking for a “real world” solution more than a purist answer. How would you write this?
Answer
Combined between Ben’s answer and this bit from Alan/Vinai’s conversation https://twitter.com/VinaiKopp/status/225318270591442945 — this is how I’m going to write it:
If the anything more than basic logic is needed, I’ll extend the class with new methods.
Otherwise, I’ll create new vars in the local scope like so:
$mynamespace_myVar = 'xyz';
This is what I like about it:
- The
$mynamespace_reminds me I created this and not Magento - It also makes it highly unlikely another developer overwrites my vars
This is what I don’t like:
- It’s un-pure and potentially corruptible, but I probably only need this <5 times for an entire site so it’s reasonably shielded.
- Not using
$_to show the var is local to this template is not “the Magento way” but it makes the code more readable.
So my templates will mostly have code like this:
$gravdept_someNiceData = true;
Some history: https://stackoverflow.com/a/3955757/833795
Re 1, 2, & 3: Differentiating between these choices involves getting into “purist answer” territory, as they are all local variables.
Using the registry pattern is uncalled for, as the desired scope is stated to be local to the rendering of the template.
Based on your example, an appropriate construction in Magento might be:
If there is anything but the simplest test of return values it’s appropriate to add this logic as a method of the block class (using a rewrite), as it is in fact view logic which you’ve mentioned should be local to this context only.