Magento 2 – How to Programmatically Check if an Order Exists Without Try-Catch

custommagento-2.1magento2modulesales-order

I am looking at the implementation of \Magento\Sales\Api\OrderRepositoryInterface
on https://github.com/magento/magento2/blob/eacac63d35b97961e3304dc007cd6b78519a93d0/app/code/Magento/Sales/Model/OrderRepository.php

According to the code, the repository will throw NoSuchEntityException if the order does not exist. However, I figure it might be expensive overtime to rely on a try-catch statement if my function gets called quite often.

Is there a command/function that I can use to just get true/false on whether an order exist by given Order ID?

Thank you,

Best Answer

There's some discussion of the overhead of exceptions in PHP here: https://stackoverflow.com/questions/104329/performance-of-try-catch-in-php

But more to the point, the overhead of exceptions (which is very small to begin with) would far and away be dwarfed by the overhead of actually checking whether the order in question exists (loading the ID in question from the database).

If your function gets called 'quite often', it might make sense to consider alternate approaches that would involve less loading from the database (depending on circumstances). Whether or not you catch exceptions isn't going to make a notable difference though.

Use exceptions the way Magento intends. They won't kill you. Be careful about trying to over-optimize the wrong things.

Related Topic