Skip to main content
3 of 3
edit code, add use statement based on the mentionned github module
ffab
  • 71
  • 9

I recently moved to Magento 2.3.2, and I had the same question

After reading this allready pointed out article (thanks https://magento.stackexchange.com/users/31910/shoaib-munir)

https://www.atwix.com/magento-2/alternatives-for-deprecated-registry-class-magento-2-3/

I found this implementation by @Vinai Kopp (https://github.com/Vinai)

https://github.com/Vinai/module-current-product-example

Basically, this trigger an observer based catalog_controller_product_init_after event for grabbing the actual displayed product and push the result into a custom registry

So after that, you can have it in your Block like the below code, or use ViewModel as suggested by @Vinai

<?php
namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;
use Vendor\Module\Registry\CurrentProduct;
 
class YourBlock extends Template
{

    /**
     * @var CurrentProduct
     */
    private $_currentProduct;

    public function __construct(
        Template\Context $context,
        ...
        CurrentProduct $currentProduct,
        array $data)
    {
        $this->_currentProduct  = $currentProduct;
        parent::__construct($context, $data);
    }


    public function getCurrentProduct()
    {
            return $this->getProductId();
    }


    /**
     * @return mixed
     */
    private function getProductId()
    {
        return $this->_currentProduct->get()->getId();
    }

}

you could also return the full product, but not sure, that is really needed

    public function getCurrentProduct()
    {
            return $this->_currentProduct->get();
    }

Hope this helps,

ffab
  • 71
  • 9