Dependency injection
If you wanted to load an order object using the order repository via the ObjectManager you would do something like:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderRepository = $objectManager->get(\Magento\Sales\Api\OrderRepositoryInterface::class);
try {
// Load order with entity_id 1
$order = $orderRepository->get(1);
} catch (\Exception $e) {
// Order not found
}
// Do something with order object
However you should inject the OrderRepositoryInterface using constructor dependency injection like so:
private OrderRepositoryInterface $orderRepository;
public function __construct(
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository
) {
$this->orderRepository = orderRepository;
)
public function someFunction()
{
try {
$order = $this->orderRepository->get(1);
} catch (\Exception $e) {
// Order not loaded
}
// Do something with order object
}
There are several reasons you should do this:
- Enables you to write testable code, allowing you to pass mock objects into your class to run test cases with,
- It is also cleaner using DI as you do not need to get instances of the class yourself,
- It allows you to use Magento's
di.xml to replace dependancies as required, for example a different areacode such as webapi_rest or frontend may benefit from a different class being injected in.