I have below code. Which give same result either I use create or get
$orderId = 1;
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$this->orderPayment = $_objectManager->create('Magento\Sales\Api\Data\OrderPaymentInterface')->load($orderId);
$this->orderPayment = $_objectManager->get('Magento\Sales\Api\Data\OrderPaymentInterface')->load($orderId);
echo $this->orderPayment->getLastTransId();
So What is exactly difference between them? Which needs to be used & when?
2 Answers 2
- $_objectManager->create() creates new instance of the object, no-matter-what
- $_objectManager->get() first tries to find shared instance (already created), if it's not found - it just creates new shared instance
If you take a look at class Magento\Framework\ObjectManager\ObjectManager, you'll notice this block:
...
/**
* Create new object instance
*
* @param string $type
* @param array $arguments
* @return mixed
*/
public function create($type, array $arguments = [])
{
$type = ltrim($type, '\\');
return $this->_factory->create($this->_config->getPreference($type), $arguments);
}
/**
* Retrieve cached object instance
*
* @param string $type
* @return mixed
*/
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];
}
...
-
create () is like "new Class()" and get () is like 'Mage::getSingleton()', it will first check the same class instance is exists or not in memory. If the instance is created then it will return the same object from memory.Chen Hanhan– Chen Hanhan2023年01月27日 11:21:04 +00:00Commented Jan 27, 2023 at 11:21
Do not use object manager (bad practice).
You have to pass \Magento\Sales\Api\OrderRepositoryInterface in construct of your class.
protected $order;
public function __construct(
...,
\Magento\Sales\Api\OrderRepositoryInterface $order
){
...
$this->order = $order;
}
Then you can do following:
$order = $this->order->get($orderId);
echo $order->getPayment()->getLastTransId();
Explore related questions
See similar questions with these tags.