The after plugin, as its name suggests, runs after the observed method.
When writing the after plugin, there are a few key points to remember:
- The first parameter coming into the plugin is an observed type instance.
- The second parameter coming into the plugin is the result of the observed method, often called $result or called after the variable returned from the observed method (as in the following example: $data).
- All other parameters are parameters of the observed method.
- The plugin must return the same $result|$data variable of the same type, as we are free to modify the value.
Let's take a look at one of Magento's after plugin implementations, the one specified in the module-catalog/etc/di.xml file:
<type name="Magento\Indexer\Model\Config\Data">
<plugin name="indexerProductFlatConfigGet"
type="Magento\Catalog\Model\Indexer\Product\Flat\Plugin\IndexerConfigData" />
</type>
The original method this plugin is targeting is the get method of the Magento\Indexer\Model\Config\Data class:
public function get($path = null, $default = null) {
// The rest of the code...
return $data;
}
The implementation of the after plugin is provided via the afterGet method of the Magento\Catalog\Model\Indexer\Product\Flat\Plugin\IndexerConfigData class, as per the following partial example:
public function afterGet(Magento\Indexer\Model\Config\Data, $data, $path = null, $default = null) {
// The rest of the code...
return $data;
}
Special care should be taken when using plugins. While they provide great flexibility, they also make it easy to induce bugs, performance bottlenecks, and other less obvious types of instabilities – even more so if several plugins are observing the same method.