0

I've question in the link below : Get grand total and customer data variables

Now I solved the issue by using object manager directly, but I found too many people said it's not recommended !

Could you please tell me why ? also is there another way to use ?

1 Answer 1

1

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.
1
  • Hi Dear, Sorry I'm beginner in PHP. I've already created custom module, how I can use you solution with my module ?
    – Dun7ill
    Aug 7, 2022 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.