Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 42 ยท Dependency Injection

Virtual Types and Constructor Arguments

Learn Magento 2 virtual types, the di.xml argument types (object, string, array, const), and how to configure classes without subclassing, with runnable stand-ins.

Suppose you need three loggers that write to three different files, or three grids that differ only in which table they read. In plain PHP you would write three subclasses, each with a constructor that calls the parent with different values. Magento offers a shorter route: a virtual type. It is a named, pre-configured variant of an existing class, defined entirely in di.xml, with no PHP file at all.

Virtual types are one half of this lesson. The other half is the vocabulary used to feed values into constructors: the xsi:type argument kinds object, string, boolean, number, null, const and array. Together they are the main way you configure Magento classes without touching their code. The real Magento XML below is read-only; the runnable examples are stand-ins in plain PHP.

Constructor arguments in di.xml

You met the type node in the last lesson. Inside it, each <argument> supplies one constructor parameter, matched by name. The xsi:type attribute says how to interpret the text:

XML
<type name="Acme\Greeting\Model\Greeter">
    <arguments>
        <argument name="prefix" xsi:type="string">Hello</argument>
        <argument name="maxLength" xsi:type="number">40</argument>
        <argument name="shout" xsi:type="boolean">false</argument>
        <argument name="formatter" xsi:type="object">Acme\Greeting\Model\TitleFormatter</argument>
        <argument name="mode" xsi:type="const">Acme\Greeting\Model\Greeter::MODE_PLAIN</argument>
        <argument name="options" xsi:type="array">
            <item name="locale" xsi:type="string">en_US</item>
            <item name="aliases" xsi:type="array">
                <item name="first" xsi:type="string">friend</item>
            </item>
        </argument>
    </arguments>
</type>
  • string, number, boolean and null give plain values.
  • object names a class, interface or virtual type that the Object Manager builds and injects.
  • const reads a PHP class constant by its fully qualified name, so XML does not copy magic strings.
  • array holds <item> children; each item has its own xsi:type, so arrays can nest and can contain objects.

The PHP constructor must have parameters named exactly prefix, maxLength and so on. A misspelled name is a common mistake: depending on the version and mode you may get an error or the value is simply never applied, so check the exact parameter spelling first.

flowchart TD
    A["di.xml type node for Greeter"] --> B["argument prefix: string"]
    A --> C["argument formatter: object"]
    A --> D["argument options: array of items"]
    C --> E["Object Manager builds TitleFormatter"]
    B --> F["Constructor call"]
    D --> F
    E --> F

Each argument is converted to a PHP value or object, then all of them are passed to the constructor.

Virtual types

A virtual type looks like this:

XML
<virtualType name="Acme\Greeting\Model\ShoutingGreeter"
             type="Acme\Greeting\Model\Greeter">
    <arguments>
        <argument name="prefix" xsi:type="string">HEY</argument>
        <argument name="shout" xsi:type="boolean">true</argument>
    </arguments>
</virtualType>

The name is unique but does not correspond to a PHP class file. When something requests ShoutingGreeter, the Object Manager builds a Greeter and applies the virtual type's arguments instead of the defaults. You then inject the variant wherever it is needed by naming it in an object argument:

XML
<type name="Acme\Greeting\Block\Banner">
    <arguments>
        <argument name="greeter" xsi:type="object">Acme\Greeting\Model\ShoutingGreeter</argument>
    </arguments>
</type>

Banner's constructor still type-hints the real class (or its interface), for example Greeter $greeter. Magento builds the virtual type, which really is a Greeter, so the type check passes. Core Magento uses this pattern heavily, for example to create several differently configured loggers, session objects and grid components from one class.

Three limits are worth remembering:

  • A virtual type is not a real class. You cannot type-hint its name in PHP code, use it with instanceof, or find it by name in generated/. You can only reference it from XML.
  • It changes constructor arguments only. If you need different behavior (new methods), write a subclass.
  • Another module can configure a virtual type by name, just like a real type, which makes virtual types easy to extend.

Factories and proxies in arguments

Two class-name suffixes appear in argument lists constantly: Factory and Proxy. A class that needs to create many objects asks for SomethingFactory in its constructor instead of calling new; a heavy dependency that is not always used can be configured as Some\Class\Proxy so it is built lazily. Both are generated code that Magento writes for you, and you do not need a PHP file for them. They have their own lesson: Factories, Proxies and Generated Code. Here you only need to know that a Proxy suffix appears in a di.xml argument like any other class name:

XML
<type name="Acme\Greeting\Model\Report">
    <arguments>
        <argument name="exporter" xsi:type="object">Acme\Greeting\Model\Exporter\Proxy</argument>
    </arguments>
</type>

A stand-in with virtual types

The stand-in registry stores real types with default arguments and virtual types that point at a real type and add their own arguments. create() merges the arguments (the virtual type's values win) and resolves nested array and object values. The type system is simplified: Magento's XML has more kinds than shown here.

PHP Virtual types over one class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Three configurations, one PHP class. Notice the last line: the virtual name is not a PHP class, which is the same limit you saw above.

The second stand-in handles the other argument kinds: constants, nested arrays and an object argument that is itself a virtual type.

PHP Argument kinds: const, array and object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The object argument built a Formatter from a virtual type whose own argument used const. In real Magento the same nesting is written with <argument> and <item> elements, exactly as in the XML above.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a virtual type?

    A virtual type reuses a real class and changes only its configuration. It has no file of its own.
  2. 2. Which statement about virtual types is true?

    Virtual types exist only in configuration, so XML can name them, but PHP code type-hints the real class or interface.
  3. 3. Which xsi:type reads a PHP class constant?

    The const type resolves a fully qualified class constant, which avoids copying magic strings into XML.
  4. 4. A di.xml argument is named logfile but the PHP constructor parameter is $logFile. What is the safest conclusion?

    Arguments are matched by constructor parameter name, so spelling and case must be identical.

Summary

  • <argument> nodes in a type supply constructor parameters by name; xsi:type selects string, number, boolean, null, object, const or array.
  • Arrays are built from nested <item> nodes and can contain objects.
  • A virtualType is a configured variant of a real class with no PHP file; inject it with an object argument.
  • A virtual type cannot be type-hinted, and it cannot add behavior; for that you need a subclass.
  • Factory and Proxy suffixes in argument values refer to generated classes.
  • The stand-ins model argument merging; real Magento has more rules (for example, argument merging across modules).

Next: Factories, Proxies and Generated Code