Magento 2 Registry & Register
Magento 2 Registry & Register
Magento 2 Registry & Register
Magento 2 registry is the next topic of Latestblog
Registry is generally used to communicate between blocks and controllers
We will go new page we will not sea registry set variable whereas session will persist and remains on new pages.
We can get current Product, Category, CMS Page by using Registry
return $this->_registry->registry(‘current_product’);
return $this->_registry->registry(‘current_category’);
return $this->_registry->registry(‘current_cms_page’);
/**
* 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’);
}
How to create custom registry
/**
* @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’);
}