Use getData() vs. magic getters in Magento 2
Video Lesson
Using getData() instead of magic getters in Magento 2 prevents naming conflicts and makes code more maintainable.
Lesson Content
Magento 2 gives us two ways to retrieve data from objects: magic getters and getData()
.
// Using a magic getter
$value = $block->getCustomViewModel();
// Using getData()
$value = $block->getData('custom_view_model');
While magic getters were introduced to provide a more "elegant" API, its behind-the-scenes conversion can cause more problems than they solve.
Let's break down what's actually happening with that magic getter first. When you call getCustomViewModel()
, Magento:
Takes your method name and removes the “get” prefix
Converts the remaining camelCase string into snake_case
Searches for that converted key in the object's data array
Returns the value if it is found
So getCustomViewModel
gets transformed into custom_view_model
before the lookup happens.
This is the exact equivalent of what getData()
is doing, passing in the same explicit name of that data object.
This would normally be ok, but this automatic conversion process can cause some really frustrating bugs, especially if you aren’t consistent with naming your objects.
Let’s look at another example, but this time, we are referencing the view model in a layout XML file with camelCase:
<argument name="customViewModel" xsi:type="object">Vendor\Module\ViewModel\Custom</argument>
And then in your PHP code, you may think you can get this value by using the same magic method approach:
$block->getCustomViewModel();
But this line actually returns null
! This is because the magic getter will convert camelCase to underscores, just as our first example did. This means it will look for custom_view_model
rather than customViewModel
.
If we look at the related getData()
method, it will work just fine, and it’s because the explicit name is used:
$block->getData('customViewModel');
This getData()
call looks for the exact name — no magic happens behind the scenes. What you see is what you get.
This is why getData()
is always the better choice.
It's explicit about which data key you're accessing
Debugging is easier since there's no hidden string conversion
You can avoid “method not found” errors when editing template files
It works consistently across all Magento versions
It performs slightly better by avoiding a string conversion process
While it requires a few extra keystrokes, using getData()
will prevent you from those late-night debugging sessions, or trying to find out why that third-party module isn’t working.