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;