Magento 2 Dependency Injection

Dependency Injection (DI) is a design pattern used in Magento 2 to manage class dependencies. Instead of creating objects manually using new or ObjectManager, Magento automatically injects required objects through the constructor.

πŸ’‘ Why Magento Uses Dependency Injection

  • πŸ§ͺ Makes code testable
  • πŸ” Supports automatic class reuse
  • πŸ” Improves security and maintainability
  • βš™οΈ Controls object creation from a single place (DI Container)

πŸ“¦ Constructor Injection Example

Magento 2 injects dependencies via class constructors.

<?php
namespace Vendor\Module\Model;

use Magento\Catalog\Api\ProductRepositoryInterface;

class Example
{
    protected $productRepository;

    public function __construct(ProductRepositoryInterface $productRepository)
    {
        $this->productRepository = $productRepository;
    }

    public function getProductById($id)
    {
        return $this->productRepository->getById($id);
    }
}
  

βœ… Magento automatically creates and injects the `ProductRepositoryInterface` object.

βš™οΈ Configuration via `di.xml` (If Needed)

You can customize DI behavior using `di.xml`.



    
    

  

🚫 Avoid Using ObjectManager Directly

❌ Don’t do this:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepo = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
  

βœ… Use DI instead (it’s cleaner and testable).

πŸ” Constructor Injection vs Factory Injection

| Method | When to Use |
|———————-|————————————-|
| Constructor Injection | For required dependencies |
| Factory Injection | For dynamic, optional, or new objects |

Example for Factory:

use Magento\Catalog\Model\ProductFactory;

public function __construct(ProductFactory $productFactory)
{
    $this->productFactory = $productFactory;
}

public function createProduct()
{
    return $this->productFactory->create();
}
  

πŸ“Œ Best Practices

  • βœ”οΈ Always prefer constructor injection
  • πŸ§ͺ Use interfaces (e.g., `ProductRepositoryInterface`)
  • 🧼 Avoid using ObjectManager directly
  • πŸ”§ Use `di.xml` only for customizations

🧠 Memory Tip: C-FAB

Remember **C-FAB** for DI patterns:

– **C**onstructor injection (most used)
– **F**actory for dynamic objects
– **A**void ObjectManager
– **B**ind interfaces in `di.xml`

βœ… Summary

  • Magento 2 uses Dependency Injection to manage class dependencies
  • DI improves testability and reduces tight coupling
  • Always use constructor injection with interfaces