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 \Magento\Framework\Registry 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 \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');
    }

    /**
     * Return catalog product object
     *
     * @return \Magento\Catalog\Model\Product
     */

    public function getProduct()
    {
        return $this->_registry->registry('product');
    }

    /**
     * Return catalog current category object
     *
     * @return \Magento\Catalog\Model\Category
     */

    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.

One thought on “Magento 2 registry object

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.