0

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!

2
  • 3
    A quick fix would be to get the business logic in a view model devdocs.magento.com/guides/v2.4/extension-dev-guide/… Nov 15, 2020 at 16:53
  • Thank you for this. I will have to look into how to do this. I am newer to Magento2, but I am trying to figure out how I would implement this in a better way and follow best practices.
    – Jonathan
    Nov 16, 2020 at 19:59

1 Answer 1

2

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

2
  • One more question. So me implementing Object:Manager once like this in my Theme list.phtml every once in a while is ok? Or should I refactor code and follow best practices. Although I am not sure how to refactor this code to make it better? I am still learning. Thanks for any help!
    – Jonathan
    Nov 16, 2020 at 20:25
  • Thank you for sharing the code in github!
    – Jonathan
    Nov 17, 2020 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.