Skip to content

Instantly share code, notes, and snippets.

@j0um
Created January 14, 2020 16:09
Show Gist options
  • Save j0um/22680131b429a3b141548e2c566d0654 to your computer and use it in GitHub Desktop.
Save j0um/22680131b429a3b141548e2c566d0654 to your computer and use it in GitHub Desktop.
Fetching a product in Magento 2 admin backend. This is an alternative to the deprecated Registry class.
namespace Vendor\CustomModule\Model\Provider;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\NoSuchEntityException;
/**
* Class Product
* @package Vendor\CustomModule\Model\Provider
*/
class CurrentProduct
{
/** @var RequestInterface */
private $request;
/** @var ProductRepositoryInterface */
private $repository;
/**
* Product constructor.
* @param RequestInterface $request
* @param ProductRepositoryInterface $repository
*/
public function __construct(
RequestInterface $request,
ProductRepositoryInterface $repository
)
{
$this->request = $request;
$this->repository = $repository;
}
/**
* @return ProductInterface
* @throws NoSuchEntityException
*/
public function get(): ProductInterface
{
$productId = $this->request->getParam('id');
$product = $this->repository->getById($productId);
return $product;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment