Magic getters on Varien_Object
(M1) and DataObject
(M2) are common practice, but with Magento 2 it feels wrong to use it.
Good:
- easy to read/write
Bad
- It causes problems when using digits in keys (see: Magento 2: different way get field of a collection or Get Custom Product attribute using camel case)
- code analyzation tools complain about non-existing methods
Question
With Magento 2 we have two new methods:
getDataByKey($key)
getDataByPath($path)
Is there any good reason to still use getData($key)
or any magic getters?
Edit:
@Vinai thanks. I did not mention the @method
method, because my approach was quite different.
It only helps the IDE, but has no impact on other things.
There are several mergedf PRs on that are "micro-optimizations" like casting to (int)
instead of intval()
or get array size outside loops (even for small arrays).
At the other hand there are
magical getters, that have some "overhead" as Marius described ....
strtolower(trim(preg_replace('/([A-Z]|[0-9]+)/', "_$1", $name), '_'));
getData($key)
mehtods also have to 2-3 additional checks ...if ('' === $key) {
if (strpos($key, '/')) {
if ($index !== null) {
For own code a totally agree to prefer real methods, but in same cases it's not possibly ... e.g. you've created a custom event ...
$value = $observer->getVar_1();
$value = $observer->getData('var_1');
$value = $observer->getDataByKey('var_1');
Using 3rd with /** @var some $value */
seem best to me. (?)