Magento 2: How to Create Root Script for Quick Testing & Debugging
Learn how to create a simple root script in Magento 2 using Bootstrap and Object Manager. This helps developers quickly test code, debug issues, and fetch data directly from Magento.
Overview
Magento 2 root script is a quick PHP file placed in the Magento root directory that allows developers to access Magento framework directly using Object Manager. It is mainly used for debugging, testing functionality, and retrieving data without creating a module.
Step 1: Create Root Script File
Create a PHP file in your Magento root directory:
<?php
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
echo "Root Script Executed Successfully";
Step 2: Run the Script
After creating the file, execute it using your browser:
Once executed, the script will run Magento bootstrap and display output directly on the page.
Important Notes
- Use root scripts only in development environment.
- Always delete script after testing is completed.
- Ensure correct path of Magento bootstrap file.
- Do not use in production servers.
Result
After executing the script successfully, you can:
- Run Magento 2 code directly
- Debug framework-level functionality
- Fetch data quickly using Object Manager
- Test Magento setup without modules