Magento2 – Registry

Magento registry stores data to memory which is specific to that request (rather than user or anything else), and persists for the duration of that request only. The principle is very simple really, the Mage class is instantiated as a singleton object for every request and the instantiated Mage object remains in memory, and is accessible in all classes (and templates) until the request completes and the response is sent.

As the object is a singleton, whenever you access it you get the same object. All that is happening is that you are storing values to this object, so when one class stores a value, and another accesses it they are both working on the same object and the second class is able to retrieve the value the first class set.

In magento 1, we were using Mage::register() and Mage::registry(). But in Magento2, the implementation is slightly different.  Here we use class Magento\Framework\Registry, and we can inject it in any constructor as follows:

namespace Excellence\Hello\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\Registry $registry)
    {
    	$this->registry = $registry;
        return parent::__construct($context);
    }
     
    public function execute()
    {
        #some code here
        
        $this->registry->register('test_var', 'this is a test!');

        #some code here
    } 
}

To access the variable, we will use following code snippet:

$this->registry->registry('test_var');

Basically, you can set a variable in registry in controller, block and access it anywhere like helper, black, model etc but only within the same request.

Note: We will have to inject the class Magento\Framework\Registry again in constructor of the class in which we are going to access the registry.