How to Use Around Plugin Magento 2 in E-Stores?
Looking to control every step of Magento product saves without touching core files? The Around Plugin Magento 2 pattern lets you wrap any public method. Developers gain precise power while store owners enjoy stable upgrades.
This article covers benefits, risks, real code, best practices, and clear alternatives.
Key Takeaways
-
Around plugins wrap core methods and use
$proceed()
to allow or block execution. -
They change inputs and outputs in one place while leaving core files untouched.
-
Before plugins suit input tweaks, after suit output changes, & around suit full control.
-
Overuse slows stores and complicates debugging.
-
Use clear sortOrder, naming, and thorough tests to avoid conflicts.
What is the Around Plugin Magento 2?
The Around plugin in Magento 2 allows you to intercept and wrap public methods of core classes.
It takes full control by using a special parameter called proceed(). This parameter determines whether the original method runs or not.
By using this plugin, you can change method inputs, skip the original code, or change the return value. The ability to run logic before and after the core method makes it flexible. Such deep control is not possible with before or after plugins.
Functionality like this comes with risks. Around plugins increase the call stack and make debugging harder. Different plugins can also conflict if not ordered or tested in a proper manner. Because of this, Magento recommends avoiding Around plugins unless needed. Always consider before plugins, after plugins, or class preferences first. Use around plugins only when no other method can meet the need.
Careful use is necessary because these plugins affect the method flow. A small mistake can stop the original method from running. That could break business logic. Proper testing and return type validation help avoid such issues. Always define a sort order to control the execution sequence of plugins. The lower the number, the earlier it runs.
Why Use Around Plugins for Magento 2 Stores?
Reason | Explanation |
---|---|
Need for Full Control Over Method Execution | Developers use around plugins to decide whether the core method runs. They wrap logic around the original method using the proceed() callback. It gives them control to apply business rules before execution. Custom checks prevent invalid calls. This level of control facilitates the management of complex workflows. |
Need to Change Input Parameters | Many situations demand input changes before Magento processes them. Around plugins allow direct modification of method arguments. It removes the need for rewriting core logic or creating extra services. Teams can pass transformed or filtered data. As a result, data flows remain consistent across the system. |
Need to Change the Return Value | Developers often need to alter the result after the original method completes. Around plugins intercept the return value and apply necessary adjustments. They can format data, mask sensitive info, or inject extra values. It enables seamless integration with third-party systems. Consistency improves across modules. |
Inject Logic Before and After Core Execution | There are cases where logic must run both before and after the original method. Around plugins provide that dual control. Teams insert logs, validations, or metrics without writing plugins. It keeps logic compact and maintainable. Testing becomes easier with a clearer execution flow. |
Avoid Inheritance Conflicts in Extensions | Magento encourages composition over inheritance. Around plugins follow this principle. They allow for behavioral changes without requiring class extensions. Modules co-exist without blocking each other. It reduces compatibility issues across third-party extensions. |
How to Use Around Plugins in Magento 2?
Step 1: Create the Plugin Class
Set up the file in your module under a path that matches its namespace.
namespace <Vendor>\<Module>\<Example>;
class ProductAttributesUpdater
{
The class name follows PSR-4 rules. Code autoloads without extra configuration.
Step 2: Define the Around Method
Add a method that targets the core save()
action.
public function aroundSave(
`\Magento\Catalog\Model\Product $subject,`
`callable $proceed`
) {
The aroundSave name hooks into save() because the first letter should be capital. $subject gives access to the product instance, and $proceed stores the original logic.
Step 3: Insert Pre-Execution Logic
Run checks or data prep before Magento touches the product.
$someValue = $this->doSmthBeforeProductIsSaved();
$returnValue = null;
The helper method sets a flag for the next step.
Step 4: Control Core Execution with proceed()
Decide if the original method should run.
if ($this->canCallProceedCallable($someValue)) {
`$returnValue = $proceed();`
}
The conditional gate keeps invalid data from hitting the database.
Step 5: Add Post-Execution Actions
React after a successful save.
if ($returnValue) {
`$this->postProductToFacebook();`
}
Use the same pattern for logs, notifications, or Magento cache updates.
Step 6: Return the Final Result
Complete the method with a valid return.
return $returnValue;
}
}
Returning the exact type preserves downstream logic.
Step 7: Register the Plugin in di.xml
Point Magento to the plugin.
<type name="Magento\Catalog\Model\Product">
`<plugin name="product_attributes_updater"`
`type="<Vendor>\<Module>\<Example>\ProductAttributesUpdater"`
`sortOrder="10"/>`
</type>
A lower sortOrder runs earlier in the chain.
Step 8: Deploy and Compile
Run' bin/magento
setup: upgrade'
and' bin/magento
setup:di: compile'
. Clear the cache to load the new class.
Step 9: Test the Workflow
Save a product in the admin. Verify that pre-checks fire, the product saves when allowed, and post-actions trigger. Inspect logs to confirm the correct path executes.
When Not to Use the Around Plugin in Magento 2?
1. When You Need to Change Input Parameters
Use a before plugin if you only want to change the input values. An around plugin is not essential in such cases. Avoid wrapping the entire method to alter arguments. That adds complexity and slows down execution. Magento offers cleaner alternatives for simple input changes.
2. When You Need to Change Return Values
Choose an after plugin when your goal is to update the output. Around plugins handle both input and output, but that flexibility increases the load. If only the return matters, there’s no need to control the entire method. Use the right plugin type to reduce performance overhead.
3. When Performance Is a Priority
Avoid around plugins in performance-sensitive code. They increase the call stack and slow down execution. The proceed()
function adds another layer. Magento discourages using them in loops or bulk operations. Select efficient plugin types to maintain system speed.
4. When Built-in Events Can Solve the Problem
Magento offers events and observers for many use cases. These work well when you don’t need full control over a method. Observers can add logic without wrapping core functions. Events also improve code separation and clarity. Check available events before writing an around plugin.
5. When You’re Unsure About proceed() Logic
Incorrect calling of $proceed()
breaks core features. You must understand when and how to call it. Skipping or misplacing it causes bugs that are hard to trace. If you're not confident in managing method flow, use a before or after plugin. Keep the logic predictable and testable.
6. When Debugging Becomes Difficult
Around plugins make stack traces harder to follow. They wrap core logic, which hides what runs. Debugging becomes time-consuming as you trace nested calls. Large projects suffer from unclear plugin behavior. Limit usage to cases where control is essential.
7. When Simpler Solutions Exist
Always explore preferences, observers, or other plugins first. Around plugins are powerful but heavy. Don’t use them because they offer full control. Simpler methods often solve the same problem with less impact. Start with light solutions and scale only when needed.
8. When Plugin Conflicts Are Likely
Avoid around plugins if multiple modules target the same method. They run in a chain and can interfere with one another. Misaligned sortOrder values or logic can break execution flow. Use simpler plugin types to reduce the chance of conflicts.
9. When Testing Environments Are Limited
If your testing setup lacks full coverage, skip around plugins. These plugins impact method flow and require precise return values. Without proper test cases, silent failures may go unnoticed. Use safer alternatives when test automation is limited.
10. When the Method Already Has Heavy Logic
Avoid wrapping methods that already perform complex tasks. Adding around plugins increases processing time and complicates debugging. In such cases, extract logic into separate services or use events to reduce overload.
11. When Code Maintainability Is a Priority
Teams with frequent handoffs should avoid around plugins. These plugins make method flows harder to trace. New developers may miss the proceed() call or fail to grasp the return structure. Choose approaches that keep logic readable and maintainable.
Around Plugin vs Before/After Plugin in Magento 2
Criteria | Around Plugin | Before/After Plugin |
---|---|---|
Execution Control | Full control over the method execution. You can choose whether to run the original method or not. | Partial control. You cannot prevent the original method from executing. |
$proceed() Usage | Requires calling $proceed() to execute the original method. Skipping it stops core execution. | No need to manage the core execution. Magento 2 runs it in an automated manner. |
Use Case | Best when you need to change both arguments and return value, or skip execution. | Ideal when you want to change inputs (before) or change output (after). |
Performance Impact | Higher impact. Increases call stack depth and may slow down execution. | Lower impact. Keeps execution lightweight and straightforward. |
Complexity Level | High. Requires careful handling of $proceed() and return types. |
Low. Simple logic that hooks into method flow in a safe manner. |
Debugging Difficulty | Harder to debug due to wrapping logic. Tracing the flow can become complex. | Easier to debug. You know when your logic runs. |
Risk Level | High risk. Misuse can break core functionality. | Low risk. Core methods always execute as expected. |
Best Use Scenarios | Use when logic needs to insert around core execution with full control. | Use when logic needs to add pre/post behavior without altering core flow. |
Magento Recommendation | Magento discourages overuse due to performance and maintenance issues. | Magento recommends these for most extension needs. |
FAQs
1. What does a Magento 2 plugin achieve compared with a class override?
A plugin wraps a target method without touching core code. An override replaces an entire class and often causes conflicts. Plugins keep the system upgrade-safe and respect Magento’s composition rules. They deliver precise control with minimal risk. Choose an override only when a plugin cannot meet the goal.
2. How does the around interceptor interact with an observed method?
The around plugin surrounds the observed method. It receives the original logic through the $proceed
callback. Your code runs first, checks conditions, then decides whether to call $proceed()
. Skipping $proceed()
stops the core action. Every around plugin must return the correct type.
3. Why must I set a unique plugin name and prefix when declaring a virtual type?
Magento identifies each plugin by its name in di.xml
. A distinctive prefix prevents clashes across modules. Clear naming also boosts readability during maintenance. A virtual type relies on the same rule, so uniqueness protects inheritance chains. Consistent labels save time in future debugging.
4. Where do I place the PHP plugin class, and how do I keep the function call signature valid?
Put the plugin class in a folder that matches its namespace. Magento’s autoloader finds the file without extra work. The plugin method starts with $subject
and $proceed
. Add any further parameters in the same order as the core method. A correct signature avoids runtime errors.
5. How does sortOrder determine which interceptor runs first on an observed method?
Magento reads the sortOrder
values when it builds the plugin chain. Lower numbers execute earlier than higher ones. The sequence matters because each Magento interceptor can alter inputs or outputs. Careful planning stops plugins from undoing each other. Set clear values to keep execution predictable.
Summary
Around plugin Magento 2 grants unmatched control over core logic. While using them, remember these key points:
-
Full Control: Wrap input, execution, and output with one plugin.
-
Conditional Execution: Skip core logic with clear business rules.
-
Performance Impact: Extra layers raise stack depth and need careful use.
-
Safer Alternatives: Prefer before, after, events, or preferences for simple tasks.
-
Testing Discipline: Confirm return types and plugin order before launch.
Consider managed Magento hosting for a customized and performance-driven e-store.