Is it bad to use ObjectManager in list.phtml like in Code Below? What's the best Practice?
-
15-04-2021 - |
Вопрос
Is it bad practice to use ObjectManager in file app/design/frontend/Smartwave/porto/Magento_Catalog/templates/product/list.phtml
like this below.
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');
if($category->getDescription())
{
echo '<div style="padding: 13px;margin-top: 15px;">'.$category->getDescription().'</div>';
}
Would there be a better way to write this???
Any help would be greatly appreciated. Thank you!
Решение
Yes
This is bad practice.
Reason why is here
https://devdocs.magento.com/guides/v2.4/extension-dev-guide/object-manager.html
But also using registry like this uses deprecated code.
There is a really good article on this
https://www.atwix.com/magento-2/alternatives-for-deprecated-registry-class-magento-2-3/
And there is some code in github
However as all things magento 2 sometimes you just need to get something done in a set amount of time.
Therefore I have no problem with this approach if moderate or not in a paid extension