Is there any way that I can specify that a Plugin X only runs when the class is called from Module Y? So that if same function is called from other modules the Plugin is not called.
1 Answer
In this case, you're probably better off using Dependency Injection to configure Module Y to use a Module Y-specific version of the class.
Any descendant can override the parameters configured for its supertype; that is, the parent class or interface:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\View\Element\Context">
<arguments>
<argument name="urlBuilder" xsi:type="object">Magento\Core\Model\Url</argument>
</arguments>
</type>
<type name="Magento\Backend\Block\Context">
<arguments>
<argument name="urlBuilder" xsi:type="object">Magento\Backend\Model\Url</argument>
</arguments>
</type>
</config>
In the preceding example, Magento\Backend\Block\Context is a descendant of Magento\Framework\View\Element\Context.
The first entry configures all instances of Magento\Framework\View\Element\Context as well as its children to pass in Magento\Core\Model\Url as $urlBuilder in their constructors.
The second entry overrides this and configures all instances of Magento\Backend\Block\Context to use Magento\Backend\Model\Url as the $urlBuilder instead.
So, if you make a modified implementation of Class, like MyClass extends Class
, you can use DI to pass MyClass to specific classes in Module Y in place of Class.
<type name="Module/Y/Model/ExampleClass">
<arguments>
<argument name="something" xsi:type="object">Module/Z/Model/MyClass</argument>
</arguments>
</type>
-
hi @Ryan, can you elaborate it please, still not cleared. I have used the same plugin class in multiple modules. Commented Jul 24, 2020 at 5:38