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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <?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(); |
Any doubts? Feel free to ask in the Comment section below.
I would be happy to answer.
Do consider sharing this post with Magento Community via social media.
Thank you.
Get Weekly Updates
Never miss Magento tips, tricks, tutorials, and news.
Thank you for subscribing.
Something went wrong.