I would love to use Magento 2's DI in some of my Magento 1 modules.
I'm not entirely sure how can I approach that and more importantly, if Magento 1 will allow me to do so ?
Most of the M1 classes extend Varien_Object. Thus, would injecting the classes the exact same way as M2 be enough to start using DI on M1 ? Something like this:
class Vendor_Module_Model_Test extends Mage_Core_Model_Abstract {
protected $_productCollection;
public function __construct(
Mage_Catalog_Model_Resource_Product_Collection $productCollection
) {
$this->_productCollection = $productCollection;
parent::__construct();
}
public myFunction($productId)
{
return $this->_productCollection->addIdFilter($productId);
}
}
1 Answer 1
The biggest question here would be do you need the Mage_Core_Model_Abstract class and an parent?
How I treat DI in Magento 1.
- If I need the class to be a "Magento" class as in
Mage::getModel('my/class')then I will not do di as it will not work with__constructso well. - If I do not need the class to be a "Magento" class then I will instantiate it with
new Class()and I can pass in the DI.
Think about your classes if they really need to be Magento classes and pick the option that fits best for you.
Explore related questions
See similar questions with these tags.