DEV Community

Cover image for Magento's DI is compiled, Laravel's is resolved: di.xml vs the service container
Nikita Sirenko
Nikita Sirenko

Posted on Originally published at linkedin.com

Magento's DI is compiled, Laravel's is resolved: di.xml vs the service container

Magento's DI looks like Laravel's container with more XML. It works more like Symfony's: it can be compiled ahead of time. That compile stops a plugin on a final class. It doesn't stop an interface nobody bound.

Same question, different moment

Both containers answer one question: which object goes into this constructor?

Laravel answers at runtime. When you resolve a class, Container::build() reads its constructor with reflection and resolves each parameter. There's no build step. A class that needs an interface nobody bound still lets the app boot. The error, "Target [ErpClient] is not instantiable while building [OrderSync]", shows up the first time something resolves it.

Magento can answer before the deploy. bin/magento setup:di:compile merges the di.xml of every module, generates the Interceptors, Factories and Proxies into generated/code, and writes the compiled configuration into generated/metadata. On a fresh Magento 2.4.9 install with a few test modules, that run took 24 seconds and produced 2,247 Interceptors, 963 Factories, 168 Proxies and 48 MB of compiled config.

Without a compile, Magento generates the same classes on first use. Delete a generated Factory and ask the object manager for it: the class still works, and the file comes back.

What the compile catches, and what it doesn't

The compile does catch some mistakes. The plugin on a final class from part 3 stops setup:di:compile with a fatal error, so it breaks the build instead of a request.

It doesn't catch the Laravel example above. A Magento class that needs an interface without a <preference> compiles without an error. The error comes on first use, the same moment as in Laravel: "Cannot instantiate interface Acme\Erp\Api\ErpClientInterface".

The everyday case: one class, its own log file

You want one service to log to its own file. Nothing else should change.

In Magento that takes 2 pieces. A virtualType is a named variant of an existing class with new constructor arguments and no PHP file behind it: here a handler for erp.log and a logger that uses it. A <type> block then hands that logger to one class.

<!-- no new PHP classes: named variants, compiled by setup:di:compile -->
<virtualType name="Acme\Erp\Logger\Handler" type="Magento\Framework\Logger\Handler\Base">
    <arguments>
        <argument name="fileName" xsi:type="string">/var/log/erp.log</argument>
    </arguments>
</virtualType>
<!-- Monolog\Logger, not Magento's Monolog: that one adds system.log -->
<virtualType name="Acme\Erp\Logger" type="Monolog\Logger">
    <arguments>
        <argument name="name" xsi:type="string">erp</argument>
        <argument name="handlers" xsi:type="array">
            <item name="erp" xsi:type="object">Acme\Erp\Logger\Handler</item>
        </argument>
    </arguments>
</virtualType>
<type name="Acme\Erp\Model\OrderExport">
    <arguments>
        <argument name="logger" xsi:type="object">Acme\Erp\Logger</argument>
    </arguments>
</type>
Enter fullscreen mode Exit fullscreen mode
class OrderExport
{
    // name="logger" in di.xml is this parameter's name
    public function __construct(private LoggerInterface $logger) {}
}
Enter fullscreen mode Exit fullscreen mode

name="logger" is the name of the constructor parameter. Write name="log" instead, and Magento ignores the argument without an error, setup:di:compile included. The class then gets the default logger: the line goes to system.log, and erp.log stays empty.

The trap: which class you base it on

The obvious base is Magento's own Magento\Framework\Logger\Monolog. Don't use it here. Array arguments in di.xml merge, so the virtual type inherits the handlers the core configures for that class: system, debug and syslog. Every line at INFO or above lands in erp.log and in system.log too, and the channel stays "main".

The core's own payment.log logger is based on the same class. It stays out of system.log only because it logs at DEBUG, and the system handler starts at INFO.

Base the virtual type on Monolog\Logger and give it a name. Then every level goes to erp.log and nowhere else, with the channel "erp".

Laravel: a channel and a contextual binding

Laravel splits the job the same way. The "erp" channel in config/logging.php is the named variant. A contextual binding in a service provider hands it to one class: when OrderExport needs a LoggerInterface, give it that channel. Other classes keep the default logger.

Since Laravel 11.20, there's also an attribute for it. #[Log('erp')] on the constructor parameter does the same thing without the provider.

$this->app->when(OrderExport::class)
    ->needs(LoggerInterface::class)
    // 'erp' channel in config/logging.php
    ->give(fn () => Log::channel('erp'));

// Laravel 11.20+: or the attribute on the constructor
class OrderExport
{
    public function __construct(#[Log('erp')] private LoggerInterface $logger) {}
}
Enter fullscreen mode Exit fullscreen mode

The trade-off

Laravel's wiring is quicker to change and easier to read: one line of PHP, and the next request uses it. Magento's needs a compile before it ships. In return, every generated class exists before the first request, and a mistake like the plugin on a final class fails the build.

The rule

Give one class a different dependency without touching the others. In Magento that's a virtual type, based on the class you actually want, and an argument on the one class that gets it. In Laravel it's a named channel and a contextual binding or an attribute. Neither container tells you about a missing binding until something asks for the class.

Next: controllers, and why every Magento 2 controller is already what Laravel calls invokable.

Have you ever used virtualType for something other than a logger?


Part 4 of 15 of the Magento 2 vs Laravel series. Originally published on LinkedIn.

Top comments (0)