Magento2 | PWA | GraphQL

How to use Registry & Register in Magento2


\Magento\Framework\Registry is the class to get and set the value of the custom attribute in Magento2.

However, you can use registry method to get information about the current Product, Category, CMS Page.

You can add the below code in your custom module block file.

for example app/code/VR/CustomModule/Block/CustomBlock.php
<?php
namespace VR\CustomModule\Block;
class CustomBlock extends \Magento\Framework\View\Element\Template
{
    protected $_registry;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,       
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {       
        $this->_registry = $registry;
        parent::__construct($context, $data);
    }

    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

    public function getCurrentCategory()
    {       
        return $this->_registry->registry('current_category');
    }

    public function getCurrentProduct()
    {       
        return $this->_registry->registry('current_product');
    }
    
	public function getCurrentPage()
	{
	    return $this->_registry->registry('current_cms_page');
	}  

}
?>
Now by using above functions in your .phtml file, you can get information about current product as well as current category.
/*for product*/
$currentProduct = $block->getCurrentProduct())
echo $currentProduct->getName() . '<br />';
echo $currentProduct->getSku() . '<br />';
echo $currentProduct->getId() . '<br />';       

/*for category*/
$currentCategory = $block->getCurrentCategory())

You can use your own logic as per above code to achieve your functionality.

  • Below code will be used to registry / register / unregister value of your custom attribute in custom module.
/**
  * @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');
}

public function getCustomVariable()
{
     return $this->registry->unregister('custom_var');
}
Tag : Magento2
0 Comments On "How to use Registry & Register in Magento2"

Back To Top