2

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?

11
  • $_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];
}
...
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

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.