Categories


Archives


Recent Posts


Categories


Magento 2: Registry Object

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

In Magento 1, it was possible to register a global variable with the static registry method.

Mage::register('some_var', 'some value');
var_dump(Mage::registry('some_var'));

Many extensions, include core Magento extensions, ended up using this from controller action methods to pass variables into the views.

While its future is uncertain (not marked explicatly supported via an @api, but not marked @deprecated) Magento 2 does have a similar registry object that should help easy the transition for extensions. The class is MagentoFrameworkRegistry, and you can inject it in any constructor.

public function __construct(//... 
    MagentoFrameworkRegistry $registry,
    //...
)
{
    //...
    $this->registry     = $registry;
    //...
}

and then set variables with

$this->registry->register('test_var', 'this is a test!');

and fetch those variables back (even from a differnt object – MagentoFrameworkRegistry is a shared/singleton object)

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

This probably violates all sorts of principles of object oriented development – but for folks who need to ship software that people use it can be a convient shortcut – just don’t forget to mark the code for future refactoring.

Confused by the dependency injection? Read the Magento Object Manager series and demystify dependency injection in Magento 2 once and for all

Copyright © Alan Storm 1975 – 2017 All Rights Reserved

Originally Posted: 16th September 2015