3

Magento registry has been deprecated since Magento V2.3+, what is the new alternative for that?

1

No,alternative is available right now.

By using a simple get() and set() function to a class, you can pass to any where at same page. A good example is given by our Dear @vinai at his a module at github. https://github.com/Vinai/module-current-product-example

The class: https://github.com/Vinai/module-current-product-example/blob/master/Registry/CurrentProduct.php#L8

1
  • nice explanation. Thanks for the help – Arbab Ahmed Oct 16 '20 at 10:05
0

I don't know your exact use case, so I'll give an example for product only.

What you can do is check if the request has any parameters. If you're dealing with a product page for example, you could get the entity id of the product and then load it via the repository class.

Product page example:

<?php declare(strict_types=1);

namespace Your\Namespace;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\RequestInterface;

class ExampleClass
{
    /**
     * @var RequestInterface
     */
    private $request;
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

    public function __construct(RequestInterface $request, ProductRepositoryInterface $productRepository)
    {
        $this->request = $request;
        $this->productRepository = $productRepository;
    }

    public function loadProduct(): ProductInterface
    {
        // Verfify if your're dealing with a product page first
        $entityId = $this->request->getParam('id');
        return $this->productRepository->getById($entityId);
    }
}

In a lot of cases this can be an alternative to the older registry method to fetch the current product.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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