Question

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!

Was it helpful?

Solution

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

https://github.com/Atwix/atwix-blog-magento2-registry-deprecated-solutions/blob/master/app/code/Atwix/RegistryAlternative/Service/GetCurrentCategoryService.php

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

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top