Now, Magento 2 has the plugins, interceptors, which allow you to execute your own code before/after calling the public class method.

Following steps to create plugin in Magento 2:

1. Create the etc/di.xml file in your module folder and add the following code there:

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="VendorName\ModuleName\Foder\SomeModel">
        <plugin name="mycompany_mymodule_plugin_modulename_foder_somemodel"
                type="MyCompany\MyModule\Plugin\ModuleName\Foder\SomeModelPlugin" sortOrder="10" />

VendorName\ModuleName\Foder\SomeModel - the name of the class whose method the plugin will be involved with;
mycompany_mymodule_plugin_modulename_foder_somemodel - unique name of your plugin formed with the plugin class name;
MyCompany\MyModule\Plugin\ModuleName\Foder\SomeModel - plugin class;
sortOrder - sets the execution priority of your plugin, among other plugins for this class.

Attention! The di.xml file can be created in the "etc" folder and in the "ect/frontend", "etc/adminhtml", etc., depending on the application area.

2. Also create the Plugin/ModuleName/Folder/SomeModelPlugin.php file for the interceptor class MyCompany\MyModule\Plugin\ModuleName\Foder\SomeModelPlugin in the module folder.

3. Add the following code in it:


namespace MyCompany\MyModule\Plugin\ModuleName\Folder;

use \VendorName\ModuleName\Foder\SomeModel;

class SomeModelPlugin
{   public function beforeSetName(SomeModel $subject, $name)
        return ['(' . $name . ')'];
  public function afterGetName(SomeModel $subject, $result)
        return '|' . $result . '|';
public function aroundSave(SomeModel $subject, callable $proceed, $arg1, $arg2)     {
if ($arg1 && subject->someTerm()){
         return $proceed($arg1, $arg2);
return null;

Before plugin is used to change the input data of the setName($name) method. It must return an array whose elements are input parameters.
After plugin - changes the getName() method result.
Around - changes the result based on the input data or disabled the execution of the standard save($arg1, $arg2) method code.

We hope you understand the principle of creating method names, thanks to the example above.

Note that if the $proceed() function is not executed, then the standard code, as well as the lower priority plugins, will not be enabled. Also, you don't have to use before, after and around at the same time.

After writing the plugin, do not forget to regenerate the Dependency injection. Run this command:

php bin/magento setup:di:compile

Remember that Magento 2 plugins cannot be applied to:

- final methods;
- final classes;
- non-public methods;
- static methods;
- constructor;
- virtual types;
- objects that are initialized before plugins loading;

You can also visit the official Magento 2 documentation to learn more about interceptor plug-ins.