Magento 2 – Create Object Using Object Manager

magento2object-manager

I want to load that $configLoader without constructor i tried like below, but it's not working please tell me any other way to load that ConfigLoaderInterface without constructor.

<?php
namespace NameSpace\Module\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Magento\Framework\Exception\LocalizedException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class CustomCommandClass extends Command
{
    public function __construct(
        \Magento\Framework\App\State $state,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Framework\ObjectManager\ConfigLoaderInterface $configLoader
    ) {
        $state->setAreaCode('frontend'); //SET CURRENT AREA
        $objectManager->configure($configLoader->load('frontend')); //SOLUTION
        parent::__construct();
    }
}

I tried like below without constructor,

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$configLoader = $objectManager->create('Magento\Framework\ObjectManager\ConfigLoaderInterface');
$objectManager->configure($configLoader->load('frontend'));

Best Answer

Please try using the object manager to test it even though is not recommended. Dependency injection must be used.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$configLoader = $objectManager->get(\Magento\Framework\ObjectManager\ConfigLoaderInterface::class);
$objectManager->configure($configLoader->load('frontend'));
Related Topic