
Run Magento 2 Code Externally
Working with Magento 2 its pretty usual, that you often needs to test or run any piece of code outside Magento. To do so, the following snippet will help you:
1 2 3 4 5 6 7 8 9 10 |
<?php use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State')->setAreaCode('frontend'); // Your Magento 2 code here |
Additional notes:
- The area code is frontend, but you change ‘frontend’ to ‘adminhtml’ to run code as if you’re in the Admin.
- You have the Object Manager in $objectManager so you can retrieve any other objects that you require.
- If the file is going to be placed in a different folder to the Magento 2 root folder, simply modify the path to app/bootstrap.php.
Enjoy!
Source: https://fishpig.co.uk/magento/tutorials/run-magento-code-externally/