Type vs Virtual Type in Magento 2
What is a Type in Magento 2 DI?
In Magento 2 Dependency Injection (DI), a type refers to an actual PHP class that is defined and configured inside di.xml. It allows developers to modify or inject dependencies into an existing class.
The <type> node is commonly used to:
- Inject constructor arguments.
- Configure plugins.
- Override class dependencies.
- Modify behavior of existing classes.
(File: app/code/VendorName/ModuleName/etc/di.xml)
This configuration modifies the dependency of the Product class by injecting a custom logger.
What is a Virtual Type in Magento 2?
A Virtual Type is a configuration-based class definition that does not exist physically in the codebase. It allows developers to create a new class configuration based on an existing class without creating a new PHP class.
Virtual types are mainly used to create multiple variations of the same class with different dependencies.
(File: app/code/VendorName/ModuleName/etc/di.xml)
This creates a virtual class CustomProduct based on Magento\Catalog\Model\Product with modified dependencies.
Using Virtual Type in Another Class
The virtual type can now be injected into other classes as a dependency.
Magento will use the virtual type configuration when resolving the dependency.
Key Differences Between Type and Virtual Type
| Feature | Type | Virtual Type |
|---|---|---|
| Definition | Represents an actual PHP class | A configuration-based class derived from another class |
| Physical Class | Exists in code | Does not exist physically |
| Purpose | Modify existing class dependencies | Create customized versions of existing classes |
| Reuse | Applies changes to the original class | Creates a separate configuration instance |
| Common Usage | Plugins, argument injection | Customizing dependency sets |
When to Use Virtual Type
- When multiple classes need different configurations of the same base class.
- When you want to avoid creating a new PHP class.
- When customizing dependencies without modifying the original class.
- When building flexible DI configurations.
Best Practices
- Use type to modify existing classes.
- Use virtualType to create variations of existing classes.
- Avoid excessive virtual types as they may make DI configurations complex.
- Use meaningful names for virtual types for maintainability.