Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento, magic getters v getData

Tags:

magento

I have been using magento for a while now and always cant decide between using the magic getter and getData()

Can someone explain the main difference, apart from the slight performance overhead (and it must be very slight).

I am thinking in terms:

  1. Future code proof (i think magento 2 will not be using magic getter)
  2. Stylistically
  3. Performance
  4. Stability
  5. Any other reasons to use 1 over the other

There is no clear way to go based on the core code as it uses a mixture of both

like image 814
Marty Wallace Avatar asked Jan 21 '13 14:01

Marty Wallace


2 Answers

There's no one answer to fit all situations and it's best to decide based on the model you are using and the particular use case.

Performance is quite poor for magic methods, as well as the extra overhead of converting from CamelCase to under_score on each accessor.

the magic methods are basically a wrapper for getData() anyway, with extra overhead.

There's is one advantage of using magic methods though, for example:

if you use getAttributeName() rather than getData('attribute_name')

at some point in the future, the model may be updated to include a real, concrete getAttributeName() method, in which case your code will still work fine. However if you have used getData(), you access the attribute directly, and bypass the new method, which could include some important calculations which you are bypassing.

like image 140
Andrew Avatar answered Oct 13 '22 23:10

Andrew


In my opinion, the safest way is to always use getData($key). The magic getter uses the same method as you already pointed out. The advantage is that you can find all references to getData in your code and change it appropriately in case the getData() method is refactored. Compare that with having to find out all magic method calls where they are always named differently. The second thing is that the magic getter can screw you up easily when you have a method which is named the same way (I think getName() got me once and it took quite some time to debug). So my vote is definitely for using getData().

like image 38
mpaepper Avatar answered Oct 13 '22 23:10

mpaepper