How to Bootstrap Magento 2 in test.php Script?

- Magento 2

Magento 2 Development; Magento 2 tutorial

The following article is dedicated to the new way to bootstrap Magento 2 in the test.php script. We shed light on the whole process and provide some useful links below.


If you’ve already done this process in Magento 1, you should know that it is possible to create a file where you need to instantiate the Mage_Core_Model_App class and then add a “dirty” code for test purposes. It is the basic example of test.php:

By using it, you enable the ability to call test.php in the browser and get a better understanding of what you are doing. The situation in Magento 2 is a little bit more complicated.

First of all, you need to create a  test.php file in the root of the Magento 2 instance:

Next, create the TestApp.php file in the same place using the following content:

Only then, you can call test.php in the browser. Note that everything that is placed in TestApp::launch() is executed.

Let’s detailly explore the aforementioned algorithm. The createApplication method in the bootstrap class creates an instance of an application class. It expects the implementation of the \Magento\Framework\AppInterface that contains 2 methods.

Therefore, you need to create your own class in TestApp to implement the interface. Make the catchException method always return false to let the app avoid handling exceptions. If something goes wrong, print it on the screen.

Next, it is necessary to implement the launch method called by \Magento\Framework\App\Bootstrap::run. Despite what the application passed as a parameter, this run method does almost the same thing. The only line that depends on the application is

Thus, calling \Magento\Framework\App\Bootstrap::run inits the Magento env as well as calls the launch method from the app leading to an important requirement: your dirty code must be put inside the method.

Then, \Magento\Framework\App\Bootstrap::run calls $response->sendResponse();. Under $response we mean what the launch method returns so that it is necessary to use return $this->_response;.

Make your app class extend \Magento\Framework\App\Http so that request and response parameters are already available. Alternatively, you can make your class extend nothing. To achieve this goal, copy the constructor from the \Magento\Framework\App\Http class and add more parameters if necessary.

We hope this article was useful. It is based on the StackExchange question by Marius and answers by Marius. For more useful articles, check out our Cookbook.