Magento 2 has a great functionality for running scripts in the command line, but sometimes you just want to quickly check something without creating a new CLI command or creating a unit test. Wouldn’t it be great if you could just write a PHP script and write some simple code in it, just to speed up your development process and not have to refresh the browser each time? Well, it turns out it’s very simple to use the Object Manager outside the Magento 2 framework. A simple example:
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
/** @var \Magento\Framework\ObjectManager\ObjectManager $objectManager */
$objectManager = $bootstrap->getObjectManager();
// your code goes here:
/** @var \Vendor\Module\Helper\Example $exampleHelper */
$exampleHelper = $objectManager->create('Vendor\Module\Helper\Example');
Now be advised: with great power comes great responsibility, and I would not suggest to use code like this in a production environment. If you want to add CLI commands, do it the Magento Way. If you want to write tests for your code, use PHPUnit with Mock data. This is purely for quick checking stuff without having to reload the page every time, or have to re-add a product to the cart and var_dump() and die() the response of your XHR request.
Visitors give this article an average rating of 4.5 out of 5.
How would you rate this article?
★ ★ ★ ★ ★