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.
2 Answers 2
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.
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() ?LinoPham– LinoPham2016年08月29日 06:47:24 +00:00Commented Aug 29, 2016 at 6:47
-
3just 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 theget()method; as best practice, prefer injecting dependencies through constructor instead of directly using the Object Manager;Alessandro Ronchi– Alessandro Ronchi2016年08月29日 07:13:38 +00:00Commented 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.Rakesh Jesadiya– Rakesh Jesadiya2016年08月29日 07:40:54 +00:00Commented Aug 29, 2016 at 7:40
Explore related questions
See similar questions with these tags.