How to Use Registry in Magento 2
Magento registry stores data to memory which is specific to a particular request and for a duration of that request only. The Mage class is instantiated as a singleton object for every request and the instantiated Mage object remains in memory and is accessible in all classes until the request completes and the response is sent.
Magento 2 allows registering global variable that supports the static registry method. But, instead of using Mage :: register() and Mage::registry() in Magento 1, apply /Magento/Framework/Registry. It accepts the settings and the registry of the restored data. In this tutorial, we will learn to create and use your own custom registry in Magento 2.
Follow the below code to use Registry in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php protected $_registry; public function __construct(\Magento\Framework\Registry $registry) { $this->_registry = $registry; } public function setRegistryVariable() { $this->registry->register('customvar', 'Value'); } public function getRegistryVariable() { return $this->registry->registry('customvar'); } public function unsetRegistryVariable() { return $this->registry->unregister('customvar'); } |
Please give us your reviews about the article which will help us perform better in further articles 🙂
Award 5 stars for our work if you found it useful!
Happy Coding!
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Thanks for sharing a such a nice Article.
Hi Rasik, thanks for appreciation 🙂