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.

asked Aug 29, 2016 at 4:50

2 Answers 2

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.

answered Aug 29, 2016 at 7:15
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');
answered Aug 29, 2016 at 5:04
3
  • Yeah. It's working. But why are we using get() neither create() ? Commented Aug 29, 2016 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; Commented Aug 29, 2016 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. Commented Aug 29, 2016 at 7:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.