I've written a console for invoicing frontend orders
https://github.com/DominicWatts/AutoInvoice/blob/master/Console/Command/Invoice.php
If I put Magento\Sales\Model\Service\InvoiceService in the constructor and run setup:di:compile magento console throws an 'Area Code Not Set' error.
You can't set area code as part of the constructor because when you run this and other console commands you see 'Area Code Already Set' error.
I understand state and why setting the 'area' is necessary.
My workaround is to do the following
use Magento\Sales\Model\Service\InvoiceService;
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->state->setAreaCode(\Magento\Framework\App\Area::AREA_GLOBAL);
$this->method();
}
public function method()
{
$this->_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$this->invoiceService = $this->_objectManager->create(InvoiceService::class);
// do stuff
}
So basically using object manager at runtime instead of injecting. I'm constantly reading that using the object manager is bad. Therefore I feel like I'm not understanding a key concept.
So my questions are this:
a) Is this the right way to work around the issue?
b) If it's not - what is the correct approach?
c) Does using object manager add resource overhead? Or is it more that it will be deprecated at some stage.