Root scripts in Magento 2 quickens the process of retrieving the data like getting the server time and store time. Creating a root script in Magento 2 helps developer to save the time. However, a root script has a problem too. In root scripts, we cannot take the complete advantage of IDE auto-completion which boosts the productivity of the developers.
By leveraging the class in a root script, the IDE starts supporting auto-completion facility. Hence, it’s a better choice for developers.
This post explains the programmatic solution to use class in root script in Magento 2.
Programmatic Solution to Use Class in Root Script in Magento 2
<?php namespace rootScript; use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $params = $_SERVER; $bootstrap = Bootstrap::create(BP, $params); $obj = $bootstrap->getObjectManager(); $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); Class rootClass { /** * @var \Magento\Framework\Stdlib\DateTime\DateTime */ private $date; public function __construct( \Magento\Framework\Stdlib\DateTime\DateTime $date ){ $this->date = $date; } public function printTime() { echo $this->date->gmtDate(); } } $rootScript=$obj->get('\rootScript\rootClass'); $rootScript->printTime();
Done! Here you go.
Do consider sharing this post with Magento Community via social media.
Thank you.