Magento 2 Registry & Register

Magento2 register global variable that supports the static registry method.

To implement register and registry method, we need to work with Mage::register() and Mage::registry() in Magento 1, but now in Magento 2 , there is a difference in running the registry. We will be required to apply \Magento\Framework\Registry, that accepts the settings and the registry of the restored data. However, we need to learn how to create or use the own custom registry and also show you how to retrieve global Magento 2 registry objects like current_category, current_product, cms page, cms_block

To get and set custom attribute in registry / register, check the following code snippet:

/**
  * @var \Magento\Framework\Registry
  */
 
 protected $_registry;
 
 /**
  * ...
  * ...
  * @param \Magento\Framework\Registry $registry,
  */
 public function __construct(
    ...,
    ...,
    \Magento\Framework\Registry $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');
}

How to get registry of current category, current product, CMS Page, CMS block

 /**
  * @var \Magento\Framework\Registry
  */
  protected $_registry;
 
 /**
  * ...
  * ...
  * @param \Magento\Framework\Registry $registry,
  */
 public function __construct(
    ...,
    ...,
    \Magento\Framework\Registry $registry,
    ...
 ) {
    $this->_registry = $registry;
    ...
    ...
 }

/**
 * Return catalog product object
 *
 * @return \Magento\Catalog\Model\Product
 */
 
public function getProduct()
{
    return $this->_registry->registry('current_product');
}
 
/**
 * Return catalog current category object
 *
 * @return \Magento\Catalog\Model\Category
 */
 public function getCurrentCategory() 
 {
     return $this->_registry->registry('current_category');
 }


/**
 * Return catalog current cms page object
 *
 */
public function getCurrentCategory()
{
    return $this->_registry->registry('current_cms_page');
}

Hope this helps you guys!

Leave a Reply