First, lets bask in the awful yet accurate glory of my original title for this quickie: Dependency Injection Argument Specific Instance Objects.
If you’ve worked your way through my Magento 2 Object Manager series, you know its possible to tell Magento’s object system that a particular object should be instantiated every time its used in automatic constructor dependency injection.
To recap, Magento defaults to using the object manager’s get
method to return objects for automatic constructor dependency injection, which will return the same object instance every time. However, if your di.xml
configuration contains the following for a specific class
<type name="FooBazBar" shared="false"/>
Magento will always instantiate a new FooBazBar
.
What I didn’t realize until today is, shared="false"
works with argument replacement as well. For example, the reader pool in Magento’s layout MagentoFrameworkViewLayout
is a separate instance from all other layout reader pools.
<!-- File: vendor/magento/magento2-base/app/etc/di.xml -->
<type name="MagentoFrameworkViewLayout">
<arguments>
<argument name="readerPool" xsi:type="object" shared="false">commonRenderPool</argument>
<argument name="cache" xsi:type="object">MagentoFrameworkAppCacheTypeLayout</argument>
</arguments>
</type>
One of the bigger challenges when working with Magento 2 has been knowing which objects are instance objects, and which aren’t. There’s no easy way to tell at a glance, and making a wrong assumption here can send you down the rabbit hole.