Magento 2 – Difference Between Create & Get ObjectManager

magento2magento2.1.5object-manager

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?

Best Answer

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