4 Key Differences Between Magento 2 Plugins and Interceptors
Are you ready to discover the key to transforming your store? Magento 2 Plugins and Interceptors are tools that let you modify features. Plugins work on specific methods, while an interceptor manages larger actions.
This article will cover the differences between plugins and interceptors for ecommerce.
Key Takeaways
-
Magento 2 Plugins and Interceptors let you customize your store effectively.
-
Examples of interceptors and plugins for ecommerce stores.
-
6 Important reasons to consider extensions over interceptors for your needs.
-
3 steps to create a plugin in Magento 2 stores.
-
A clear comparison table showing the key differences between plugins and interceptors.
-
6 Factors to Considered Between Inceptors and Plugins in Adobe Commerce
-
4 Key Differences Between Magento 2 Plugins and Interceptors
What is the Magento 2 Plugin?
Magento 2 Plugin is a powerful tool. It allows developers to change the action of public class functions.
Magento 2 plugin works by blocking an action. It is done within the Magento framework. Plugins enable you to execute personalized code. The approach allows for flexibility in extending or replacing the functionality. Extensions can adjust the arguments of an observed method or the progress of the same process.
They help developers adjust the behavior of a class method. Plugins target specific public methods to keep Magento solutions modular.
3 Real-World Examples of Magento 2 Plugins (Modifiers)
1. Amazon: Dynamic Product Recommendations
Amazon shows personalized product recommendations to enhance the shopping experience. A plugin can block the getProductCollection() method. It adds logic that displays suggestions based on the customer’s preferences. This makes recommendations more relevant to the user’s browsing or purchase history.
Plugin Type: An around plugin wraps the product collection method. It adds custom logic around the action to display personalized recommendations.
2. Nike: Dynamic Pricing Adjustments
Nike uses dynamic pricing to offer discounts during sales or promotions. A plugin can block the getFinalPrice() method. It helps to apply rules for customer-specific prices or active discounts. This ensures the right price is shown without changing the core system.
Plugin Type: A before the plugin modifies the price using a modified argument before it is shown. This avoids the need to replace a method.
3. Sephora: Loyalty Points Allocation
Sephora offers loyalty points for purchases to reward customers and encourage repeat business. A plugin can block the placeOrder() method. It helps to calculate and assign loyalty points based on the order total. Points are added to the customer’s account after the order is placed.
Plugin Type: An after-plugin updates the customer’s loyalty balance. It is based on the results of an observed method. This ensures the loyalty system works seamlessly.
What is the Magento 2 Interceptor?
Magento 2 Interceptor is a mechanism. It is used to adjust or extend the functionality of public methods in Magento.
Magento 2 Interceptor without altering the core code. Interceptors utilize a design guide to execute custom logic. The approach ensures that developers can add customizations while maintaining modularity. By focusing on specific methods, filters allow adjustments. It includes changing method inputs or controlling the method’s execution flow. They are designed to work seamlessly within Magento’s framework.
3 Real-World Examples of Magento 2 Interceptors
1. eBay: Dynamic Product Discounts
eBay offers discounts during promotions or for customer groups around the world. An interceptor class can target a call to an observed method. It includes getFinalPrice() to calculate discounts and keeps the system flexible. It also avoids the required modification of the Magento framework.
Interceptor Use: An around-the-method block wraps the pricing logic. It adds discount calculations around that action. This ensures accurate discounts without changing the Magento base.
2. Best Buy: Fraud Detection During Checkout
Best Buy ensures safe payments by validating orders for fraud during checkout. A Magento 2 extension can use an interception add-on. It blocks the placeOrder() method and runs fraud checks. It includes verifying payment details or analyzing customer history before processing the order.
Filter Use: An around methods block wraps the checkout process. It includes fraud checks and ensures fraud detection runs using an observed function. This works smoothly within the Magento platform.
3. IKEA: Real-Time Stock Validation
IKEA syncs inventory with external systems to ensure accurate stock availability. A filter class can block restricted methods to fetch real-time stock updates. It prevents overselling and improves the shopping experience for customers.
Interceptor Use: An around-methods filter wraps the stock validation logic. It ensures inventory checks are done correctly without adjusting Magento's default behavior.
6 Factors to Considered Between Inceptors and Plugins in Adobe Commerce
1. Purpose
-
Interceptors: These tools let you change public classes or methods using a filter pattern. They work well for broad changes but lack focus for specific tasks.
-
Plugins: Plugins let you modify specific methods without altering the original class. They excel at making precise, targeted changes for advanced needs.
2. Ease of Use
-
Interceptors: Interceptors are abstract and complex to use without deep technical knowledge.
-
Plugins: Plugins are simple and developer-friendly. By following clear rules in the di.xml file, you can create and manage them easily. It makes plugins quick to build and fix.
3. Flexibility
-
Interceptors: They offer a broad way to change behavior but lack precision for specific tasks.
-
Plugins: Plugins are flexible and precise. They target specific methods, giving developers better control and aligning with exact business needs.
4. Conflict Resolution
-
Interceptors: These handle conflicts conceptually but lack tools for managing priorities or execution order.
-
Plugins: Plugins shine in handling conflicts. Using the sortOrder setting in the di.xml file, you can decide the execution order for smooth integration.
5. Performance
-
Interceptors: They can hurt performance by intercepting all calls using targeted methods, even when not needed.
-
Plugins: Plugins improve performance optimization by focusing only on specific methods. They reduce unnecessary processing, making them faster and more efficient.
6. Real-world Applications
-
Interceptors are suitable for broad, general-purpose changes but unsuitable for precise tasks.
-
Plugins: Plugins excel in real-world tasks like dynamic pricing, inventory updates, and loyalty programs. They let you add custom features without disrupting Magento's stability.
3 Steps to Create a Plugin In Magento 2
Step 1: Create the etc/di.xml File in Your Module Folder
Add the following code to the di.xml file:
`
<type name="VendorName\\ModuleName\\Folder\\SomeModel">
<plugin name="mycompany_mymodule_plugin_modulename_Folder_somemodel"
type="MyCompany\MyModule\Plugin\ModuleName\Folder\SomeModelPlugin"
sortOrder="10" />
</type>
-
VendorName\ModuleName\Folder\SomeModel: The name of the type or method the plugin will change.
-
mycompany_mymodule_plugin_modulename_Folder_somemodel: A unique plugin name, often based on the plugin class name.
-
MyCompany\MyModule\Plugin\ModuleName\Folder\SomeModelPlugin: The plugin class containing the plugin logic.
-
sortOrder: Sets the priority of the plugin if multiple B2B extensions are applied to the same type or method.
Note: Place the di.xml file in etc or specific areas like etc/frontend or etc/adminhtml, depending on the scope of the module.
Step 2: Create the Plugin Class File
Create the file in your module folder: Plugin/ModuleName/Folder/SomeModelPlugin.php.
Step 3: Add Code to the Plugin Class
Add the PHP code to the SomeModelPlugin.php file:
`<?php
namespace MyCompany\MyModule\Plugin\ModuleName\Folder;
use \VendorName\ModuleName\Folder\SomeModel;
class SomeModelPlugin
{
/* Magento 2 before plugin example */
public function beforeSetName(SomeModel $subject, $name, $storeId = 0)
{
return ['(' . $name . ')'];
}
/* Magento 2 after plugin example */
public function afterGetName(SomeModel $subject, $result, $name, $storeId \= 0)
{
return '|' . $result . '|';
}
/\* Magento 2 around plugin example \*/
public function aroundSave(SomeModel $subject, callable $proceed, $fields, $customData)
{
if ($someCondition) {
return $proceed($fields, $customData);
}
return null;
}
}`
-
beforeSetName: A before plugin example that changes input parameters. It is before the method is called.
-
afterGetName: An after plugin that updates the output after the observed method ends.
-
aroundSave: An around plugin that controls the action and running code. It can add conditions to change the action of the same class or continue with the default method call.
4 Key Differences Between Magento 2 Plugins and Interceptors
Aspect | Plugins | Interceptors |
---|---|---|
Developer Access | Interceptors work inside Magento’s framework and cannot be implemented directly by developers. | Plugins are easy to use and require simple configurations in di.xml to add custom logic. |
Use Cases | They are ideal for tasks like dynamic pricing or loyalty programs. It is for logic after an observed function is completed. | They provide general interception. It lacks precision for real-world tasks. |
Scope | They target specific observed methods correctly, allowing precise customizations. | Filters operate broadly and work on any eligible class. |
Configuration | They need an explicit setup in di.xml. It defines default values, extension, and execution order. | No setup is required for interceptors. They are part of Magento’s core system. |
FAQs
1. How can Magento 2 Plugins enhance functionality?
Modifiers help developers adjust the behavior of specific public methods. It can block method calls without changing Magento’s core code. It adds custom logic before, after, or around them. It allows you to extend built-in functionality while keeping the system intact.
2. What is the role of around extensions in Magento 2?
Around extensions in Adobe Commerce give you complete control over how a method runs. You can add your custom logic around methods before or after they execute. It lets you change inputs, control outputs, or skip the method’s original behavior.
3. Can plugins work alongside observers in ecommerce stores?
Extensions and observers can be used together. It focuses on specific methods, while observers react to system-wide events. Using both allows you to make detailed methods. It changes when responding to global system events. This gives you more flexibility in customizations.
4. What is an example of how a Magento 2 plugin works?
A standard add-on example is modifying product prices. For example, a plugin can block the getFinalPrice() method. It applies a discount based on customer group or a promotion. This allows you to change the price logic dynamically without affecting core files.
5. How can I set up a plugin in Adobe Commerce?
To create a plugin, first, define the plugin in the di.xml file, specifying the method and class you want to target. Write the plugin logic in the extension. Use before, after, or around methods based on when you want your code to run. The setup ensures you can safely modify Magento's behavior.
6. What should I check if a plugin is not working?
If a plugin does not work as expected, check the di.xml configuration for Magento errors. Ensure that the sort order is correct. The method name matches and the extension has no syntax issues. You can also use Magento’s debugging tools to track down issues.
Summary
Magento 2 Plugins and Interceptors help developers change how methods work. Plugins allow you to add custom logic before, after, or around a technique. Interceptors block methods to safely extend Magento's functionality. Consider the following when choosing the best extension:
-
Choose Magento 2 Plugins if you need precise control over specific methods. They let you change method behavior before, after, or around execution.
-
Choose Magento 2 Interceptors if you need to block method calls. They can extend functionality but do not offer the same control as extensions.
Explore Magento Hosting Plans to find the best fit for your e-commerce business needs.