
Today we learn how to create Inceptor or plugin in Magento 2. At development time we need to change some function behavior so Magento provides a plugin for it.
A Plugin or Inceptor allows change behavior of any public class or method by intercepting a function call and running code. Plugins are only used for “public methods”.
A plugin can be declared in the di.xml file in your module.
app/code/VendoreName/ModuleName/etc/di.xml
<config>
<type name="{ObservedType}">
<plugin name="{pluginName}" type="{PluginClassName}" sortOrder="1" disabled="false" />
</type>
</config><type name="Dolphin\PluginDemo\Controller\Index\PluginExample">
<plugin name="demo_plugin" type="Dolphin\PluginDemo\Plugin\PluginDemo" sortOrder="1" disabled="false" />
</type>For example, the following code defines type name, we created PluginExample.php file at app/code/Dolphin/PluginDemo/Controller/Index/PluginExample.php
if you don’t know how to create module click here
<?php
namespace Dolphin\PluginDemo\Controller\Index;
class PluginExample extends \Magento\Framework\App\Action\Action
{
protected $title;
public function execute()
{
echo $this->setTitle('Welcome Plugin');
echo $this->getTitle();
}
public function setTitle($title)
{
return $this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
Find here for more plugins: Magento 2 Extension
<?php
namespace Dolphin\PluginDemo\Plugin;
class PluginDemo
{
public function beforeSetTitle(\Dolphin\PluginDemo\Controller\Index\PluginExample $subject, $title)
{
$title = $title." Before plugin method is calll</br>";
return [$title];
}
}<?php
namespace Dolphin\PluginDemo\Plugin;
class PluginDemo
{
public function afterGetTitle(\Dolphin\PluginDemo\Controller\Index\PluginExample $subject, $result)
{
echo "After plugin method call</br>";
return $result . 'Modify Result';
}
}<?php
namespace Dolphin\PluginDemo\Plugin;
class PluginDemo
{
public function aroundGetTitle(\Dolphin\PluginDemo\Controller\Index\PluginExample $subject, callable $proceed)
{
echo "Around Method Call"
$result = $proceed();
echo "Around Method Call over"
return $result;
}
}Plugins are commonly used in Magento development.
I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.
Click one of our contacts below to chat on WhatsApp