5

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);
 }
}
asked Oct 31, 2016 at 8:47

1 Answer 1

6

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.

  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 __construct so well.
  2. 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.

answered Oct 31, 2016 at 9:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.