In Magento 2, the Registry Object and Register play pivotal roles in storing and retrieving data throughout a session. The Magento 2 Registry Object acts as a temporary data storage space during a user’s session. It allows you to pass data across different parts of your application without the need for cumbersome global variables.
Imagine you’re developing a module that allows users to leave product reviews, and you need to display the currently viewed product within the review form. You can use Magento’s registry to store and retrieve the current product.
First, you would store the product in the registry. This might happen in a controller:
public function execute()
{
//Get product by id from the repository
$productId = $this->getRequest()->getParam('product_id');
$product = $this->productRepository->getById($productId);
//Check if product exists
if ($product->getId()) {
//Register the product
$this->coreRegistry->register('current_product', $product);
}
}
In the above code, we use
$this->coreRegistry->register('current_product', $product);
to store the product in the registry under the key ‘current_product‘.
Later, you can retrieve the product from the registry in a block that generates the form:
public function getCurrentProduct()
{
return $this->coreRegistry->registry('current_product');
}
The function getCurrentProduct()
returns the product that was stored in the registry, which can then be used in your form template.
Remember, the registry is a global storage, so be cautious when using it. Avoid using common names for your registry keys to prevent conflicts. Always check if a key is already registered before using it, and be sure to unregister
$this->coreRegistry->unregister('current_product')
it when you’re done.
Thank you for reading my Article! Feel free to share your thoughts or ask any questions in the comments section below and spread the word by sharing. Your engagement is appreciated!