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