3

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?

asked Mar 13, 2017 at 7:06

2 Answers 2

13
  • $_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];
}
...
Prince Patel
23.1k10 gold badges102 silver badges124 bronze badges
answered Mar 13, 2017 at 8:19
1
  • 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. Commented Jan 27, 2023 at 11:21
0

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();

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.