I'm trying to use the
\Magento\Sales\Model\InvoiceOrder class to invoice some orders. If I include the class in my constructor, however, then I get the "Area code not set: Area code must be set before starting a session." error.
I ran a
bin/magento setup:di:compile -vvv and found that the exception is being thrown while initialising the "Magento\Payment\Helper\Data" class which requires
Magento\Ui\Config\Reader\Definition\Data and goes on to run
Magento\Framework\Url->getUrl() which in turn attempts to create a session.
Is there any way to make this work? I can think of three ways to possibly make it work, but I'm not sure if any of them would be considered best-practice:
- Use the ObjectManager to get the instance of "InvoiceOrder" rather than Dependency Injection.
- Set the Area somewhere, like a class constructor, so it can bypass the issue
- Extend one of the base classes (like "\Magento\Framework\Url") with a plugin which either sets the area or catches the exception.
I'm getting around the issue right now using the Object Manager, but it obviously goes against best practices. Would option 3 be considered good practice, or at-least better practice than the other two options? It seems a bit crazy to set the area in a console command even though it won't really be used.