skip to Main Content

How to avoid using depricated Registry and prohibited Object Maneger to get current product? I have this code now:

        $objectManager = MagentoFrameworkAppObjectManager::getInstance();
        $product = $objectManager->get('MagentoFrameworkRegistry')->registry('current_product');
        $product = $objectManager->create('NameModuleNameModelFolderProduct')->load($product->getId());

2

Answers


  1. If you haven’t already, you might like to try "Alternatives for deprecated Registry class – Magento 2.3" by Burlacu Vasilii, which can be found here:
    https://www.atwix.com/magento-2/alternatives-for-deprecated-registry-class-magento-2-3/

    It seems Registry was deprecated because keeping data in Registry proved to be a kind of lottery. So, if a developer cannot use Registry to get data, the answer then is essentially “from the session”.

    The example he uses is to, "Add a Back to [category name] link on the product view page"; below the product name.

    Login or Signup to reply.
  2. The correct way of getting the current product on PDP page without using registry class is to use Catalog Helper class.

    public function __construct(    
        MagentoCatalogHelperData $catalogHelper
    ) {
        $this->catalogHelper = $catalogHelper;
    }
    
    public function run() {
        $this->catalogHelper->getProduct();
    }
    

    By looking at the implementation you will see that it is still using registry class under the hood, but that is okay because when core class will be refactored to not use registry class, your code will not break and you should still get your product. This is the whole purpose of the helper class, essentially you are shifting responsibility to the framework from your own implementation, which is the best you can do in this scenario.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search