Magento 2 registry object


Same as Magento 1, Magento 2 also allows you to have registry to register global variable using
static registry method -:

In Magento 2, Mage::registry has become MagentoFrameworkRegistry which has two key methods to set or retrieve registry variable. These two methods are register for setting and registry for retrieving data.

In this tutorial we are going to Magento 2 registry object and show you how you can create or use your own custom registry and also show you how to retrieve global Magento 2 registry objects like current product, category, cms page, cms block etc.

Here is the quick code snippet to help you work with Magento 2 registry objects

 /** * @var MagentoFrameworkRegistry */ protected $_registry; /** * ... * ... * @param MagentoFrameworkRegistry $registry, */ public function __construct( ..., ..., MagentoFrameworkRegistry $registry, ... ) { $this->_registry = $registry; ... ... } /** * Setting custom variable in registry to be used * */ public function setCustomVariable() { $this->registry->register('custom_var', 'Added Value'); } /** * Retrieving custom variable from registry * @return string */ public function getCustomVariable() { return $this->registry->registry('custom_var'); } /** * Return catalog product object * * @return MagentoCatalogModelProduct */ public function getProduct() { return $this->_registry->registry('product'); } /** * Return catalog current category object * * @return MagentoCatalogModelCategory */ public function getCurrentCategory() { return $this->_registry->registry('current_category'); } 

That’s it, it is as simple as that. Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Discover more from WHO WILL CARE eCommerce

Subscribe now to keep reading and get access to the full archive.

Continue reading