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?