credits: Seagull ST19 Detail via photopin (license). posted on June 23rd, 2016.

Quickly run Scripts in the Shell in Magento 2

A simple hack

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:

require '/absolute/path/to/app/bootstrap.php';
$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');
$exampleHelper->doSomething();

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 (and do it the Magento Way).

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.

Magento 2 Php Shell CLI