One of the biggest problems in Magento 1.x was that changing the behavior of a function in a class that didn't have an event trigger had to be rewritten. This works fine if only a single rewrite for a class was used, but when using a large number of extensions, there is a risk that multiple extensions rewrite the same class, which can result in unpredictable results.
In Magento 2, this problem is partly solved by introducing Interception in the form of plugins. With the use of plugins, it is possible to modify a function in three places:
The use of plugins is controlled through di.xml
. It is possible to use the global from etc
/ or the area specific from etc/[area]
; in this case, we will use the global, which means that it is used in all areas.
Create the following files in this recipe to try the use of plugins:
di.xml
:etc/di.xml
<type name="MagentoCmsModelPage"> <plugin name="sample_before" type="GenmatoSamplePluginBeforePage" sortOrder="1"/> </type> <type name="MagentoCatalogModelProduct"> <plugin name="sample_around" type="GenmatoSamplePluginAroundProduct" sortOrder="1"/> </type> <type name="MagentoCmsModelPage"> <plugin name="sample_after" type="GenmatoSamplePluginAfterPage" sortOrder="1"/> </type>
Plugin/BeforePage.php
<?php namespace GenmatoSamplePlugin; use MagentoCmsModelPage; class BeforePage { public function beforeSetContent(Page $subject, $content) { return $subject->setContent('<!--'.$content.'-->'); } }
Plugin/AroundProduct.php
<?php namespace GenmatoSamplePlugin; use MagentoCatalogModelProduct; class AroundProduct { public function aroundSave(Product $subject, Closure $proceed) { $subject->setMyCustomAttribute('sample'); $return = $proceed(); $subject->setMyCustomAttribute(''); return $return; } }
Plugin/AfterPage.php
<?php namespace GenmatoSamplePlugin; use MagentoCmsModelPage; class AfterPage { public function afterGetTitle(Page $subject, $result) { return 'SAMPLE: '.$result; } }
bin/magento cache:clean
All configured interceptors/plugins are evaluated during initialization. When a call is made to a function that is extended through a plugin, all plugin functions are executed based on the configured sortOrder
as configured in di.xml
. If there are multiple plugins that extend the same original function, they are executed in the following sequence:
sortOrder
sortOrder
sortOrder
)sortOrder
)sortOrder
sortOrder
)There are some limitations on where you can use plugins; it is not possible to use plugins for the following:
__construct
If you need to modify one of these types listed, the only option to do this is to rewrite (preference) your class through di.xml
.
3.133.123.126