Plugin in Magento 2
What is a Plugin?
In Magento 2, a plugin (also called an interceptor) is a way to modify the behavior of public methods in a class without overriding the entire class.
It’s part of Magento’s interception system and is often used instead of preference to keep your code modular and upgrade-safe.
How Plugins Work
A plugin lets you "hook into" a method of any public function of a class and run your logic:
- Before Method → runs before the target method.
- After Method → runs after the target method.
- Around Method → wraps around the target method (you can even stop execution).
Example: Create a Plugin
Suppose we want to add custom logic before a product is saved (\Magento\Catalog\Model\Product::save()).
1. Create di.xml
(File: app/code/VendorName/ModuleName/etc/di.xml)
2. Create Plugin Class
File: app/code/VendorName/ModuleName/Plugin/ProductPlugin.php
Rules / Best Practices
- You can only use plugins on public methods.
- If multiple plugins exist for the same method, execution order is controlled by
. - Prefer before/after unless you need to control execution flow (then use around).
- Use around carefully → it can completely replace method execution if you don’t call $proceed().