Skip to main content

Virtual Types

What Are Virtual Types?

Virtual types in Magento 2 are non-instantiable configurations defined in the DI (Dependency Injection) container. They allow you to create a new "type" based on an existing class with modified arguments.

When to Use

Use virtual types when you:

  • Need a variation of a class with different constructor arguments.
  • Want to inject different dependencies without creating a new subclass.
  • Need to override specific services conditionally or modularly.

Examples

<virtualType name="CustomLogger" type="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="name" xsi:type="string">custom</argument>
</arguments>
</virtualType>

Best Practices

  • Keep naming consistent and clear.
  • Avoid overusing virtual types for simple customizations.