4

I'm initializing an object \Magento\Framework\Registry via a function create() of Magento\Framework\ObjectManagerInterface in Controller. After, I try to register a value to Registry Class.

$registry = $this->_objectManager->create('Magento\Framework\Registry');
$registry->register('test', '123456');

I try to get this value in Block. However, it return null.

$registry->registry('test'); //return null

If I inject \Magento\Framework\Registry to the constructor, it working normally.

public function __construct(
    Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Registry $registry
) {
    parent::__construct($context);
    $this->registry = $registry;
}

My question: Why this two ways different initialization?

Any help is appreciated.

1

why are we using get() neither create() ?

Create always Create new object instance

Ref

public function create($type, array $arguments = [])
{
    $type = ltrim($type, '\\');
    return $this->_factory->create($this->_config->getPreference($type), $arguments);
}

Get retrieve existing object instance(if find any)

public function get($type)
{
    $type = ltrim($type, '\\');
    $type = $this->_config->getPreference($type);
    if (!isset($this->_sharedInstances[$type])) {
        $this->_sharedInstances[$type] = $this->_factory->create($type);
    }
    return $this->_sharedInstances[$type];
}

For more information please check

\vendor\magento\framework\ObjectManager\ObjectManager.php

Hope it helps.

1

You need to define registry using get() method and its working same as constructor,

$registry = $this->_objectManager->get('Magento\Framework\Registry')->register('test', '123456');

and getting registry value using below method,

$this->_objectManager->get('Magento\Framework\Registry')->registry('test');
  • Yeah. It's working. But why are we using get() neither create() ? – Bill Aug 29 '16 at 6:47
  • 3
    just to add some more clarification: the create() method returns a new instance which is different from the one already instantiated by the Object Manager; this one can be retrieved by the get() method; as best practice, prefer injecting dependencies through constructor instead of directly using the Object Manager; – Alessandro Ronchi Aug 29 '16 at 7:13
  • I have same issue as you but i have debug using get method to its working, I am still not know why create method is not working. – Rakesh Jesadiya Aug 29 '16 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.