Categories


Archives


Recent Posts


Categories


Magento 2: shared=“false” works for specific arguments

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

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.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 8th June 2016

email hidden; JavaScript is required