As per object oriented programming concept, an interface can not be initialised directly but can be used to implement in other class and the instance of that class can be created. So my question is how Magento allows to create instance of interface in DI(constructor) ?

For example StoreManagerInterface in following sample code

public function __construct(
\Magento\Backend\Block\Template\Context $context,        
\Magento\Store\Model\StoreManagerInterface $storeManager,        
array $data = []
    $this->_storeManager = $storeManager;        
    parent::__construct($context, $data);

Interfaces can never be initialized. In magento 2 it also follows the same logic. but if you go to the magento-root/app/etc/di.xml on the line 32 you will find this:

<preference for="Magento\Store\Model\StoreManagerInterface" type="Magento\Store\Model\StoreManager" />

This line defines the preference on the interface, as whenever this interface is called for initialization the dependency injection will inject this class "Magento\Store\Model\StoreManager" in place of it. So the object you are getting there is the object of this StoreManager Class.

| improve this answer | |
  • Great explanation. But I have query regarding this. Why Magento recommend to use interface in DI constructor ? Because in such case we can use class Magento\Store\Model\StoreManager directly instead of Magento\Store\Model\StoreManagerInterface – Kishan Patadia Aug 7 '19 at 11:29
  • To the best of my knowledge, Its a fairly new design pattern introduced by magento. By this pattern you should only call the functions defined in the interface where ever you use its object, not the function defined in its concrete class as a standard and its done by the magento in the core class. So if you dont like the implementation of this class by magento. Simply create you own class, implement the interface and its functions. Define the preference of your class on this interface. and you are good to go without any crashes. – Muhammad Mannan Masood Aug 7 '19 at 13:21
  • you don't have to write the whole class. And also there might be more magento classes that uses the functions defined in its concrete class of the interface so it will not break them too. – Muhammad Mannan Masood Aug 7 '19 at 13:21
  • Please accept this as the answer if it helped. Thanks – Muhammad Mannan Masood Aug 19 '19 at 9:48

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.