Sunday, April 19, 2026
Magento

di.xml Generator

Generate Magento 2 dependency injection configuration XML for plugins, preferences, and virtual types.

Configuration
Generated di.xml & PHP Skeleton
// Configure options on the left to generate di.xml configuration

How to Use the Magento 2 di.xml Generator

The di.xml Generator produces Magento 2 dependency injection configuration XML along with the matching PHP class skeleton. Choose between plugins (interceptors), preferences (class rewrites), and virtual types, fill in the class names, and get complete, copy-paste-ready code in seconds.

Magento 2's DI system is central to every customization. Instead of extending and overriding core classes with PHPCS hacks, the framework provides structured mechanisms: plugins let you intercept method calls non-destructively, preferences replace an entire class for a given interface or implementation, and virtual types create preconfigured instances without writing new PHP files.

Plugin vs Preference vs Virtual Type

  • Plugin (Interceptor) — The preferred extension method. Intercept any public method with a before, after, or around wrapper. Multiple plugins on the same method coexist via sortOrder. Does not break other plugins or customizations on the same class.
  • Preference (Class Rewrite) — Replaces an entire class or satisfies an interface binding. Use only when a plugin cannot achieve the goal (e.g., adding a constructor parameter, modifying a private method's behavior). Only one preference per interface/class is active — conflicts require a third class that extends both.
  • Virtual Type — Creates a named instance of an existing class with specific constructor arguments, without writing a new PHP file. Widely used for loggers, connection configurations, and collection factories.

Common Mistakes

  • Forgetting that plugins only work on public methods. Private and protected methods cannot be intercepted.
  • Using a preference when a plugin would work — preferences block other modules from plugging the same class, increasing conflict risk.
  • Placing di.xml in the wrong area. Global di.xml lives in etc/di.xml; frontend-only configuration goes in etc/frontend/di.xml.
  • Not running bin/magento setup:di:compile after adding or changing di.xml entries — the generated interceptors and factories will not be updated otherwise.