0

I am working on some custom scripts to import some data before a new store is launched. These scripts are needed only once and will not play any role after launch. They are supposed to be executed on the command line (not via browser).

In Magento 1 it was as easy as to require app/Mage.php and then get going.

In M2 whenever I need a class to do something I am supposed to inject them into another class via constructor. So my custom script becomes a class itself which is not a bad thing (a bazillion lines of spaghetti code are proving me right).

Also using the object manager directly is highly discouraged.

So I want to do it right:

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/../app/bootstrap.php';
require dirname(__FILE__) . '/Attributes.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$app = $bootstrap->createApplication('Attributes');
$bootstrap->run($app);


class Attributes extends \Magento\Framework\App\Http implements \Magento\Framework\AppInterface
{
    protected $_db;
    protected $_eav_factory;
    protected $_attribute_factory;
    protected $_store_manager;
    protected $_csv;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $db,
        \Magento\Eav\Setup\EavSetupFactory $eav_factory,
        \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute_factory,
        \Magento\Store\Model\StoreManagerInterface $store_manager,
        \Magento\Framework\File\Csv $csv
    ) {
        $this->_db = $db;
        $this->_eav_factory = $eav_factory;
        $this->_attribute_factory = $attribute_factory;
        $this->_store_manager = $store_manager;
        $this->_state = $state;
        $this->_csv = $csv;
        $this->_state->setAreaCode('frontend');
    }

    public function launch()
    {
        // let the magic happen
    }
}

Above code does not work: Uncaught TypeError: Argument 1 passed to Attributes::__construct() must be an instance of Magento\Framework\App\ResourceConnection

So my question is: when I am supposed to use classes and proper dependency injection, how can I get those classes into my custom class?

  • You should try this with custom module, you can create a new command for this and write your logic in that class. – Ramkishan Suthar Oct 22 '18 at 16:32
1

When should you use classes? I would say that all the time.

Proper dependency injection? When you need some other class in your class - also all the time, as you wrote using ObjectManager is highly discouraged.

In your situation just create a custom module with a CLI class -> https://devdocs.magento.com/guides/v2.2/extension-dev-guide/cli-cmds/cli-howto.html and DI will work without any extra configuration.

  • Perfect, that's the way I will go. Thank you. – omsta Oct 23 '18 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.