Magento 2 is highly flexible, allowing developers to customize its functionality without changing the core code. One popular way to customize functionality is through plugins. Plugins let you change how Magento methods work. There are three types of plugins in Magento 2: Before, After, and Around.
In this guide, we’ll learn how to use an After Plugin with parameters to customize a specific Magento method.
The Problem: Customizing getCategoryUrl()
The method we want to customize is getCategoryUrl()
in the Magento\Catalog\Helper\Category
class:
public function getCategoryUrl($category)
{
if ($category instanceof ModelCategory) {
return $category->getUrl();
}
return $this->_categoryFactory->create()->setData($category->getData())->getUrl();
}
This method generates a URL for a category. The $category
parameter is either a ModelCategory
object
or an array of category data. We want to modify the result of this method based on the $category
object.
The Challenge with After Plugins
An After Plugin allows us to change the result of a method, but it doesn’t automatically give access to the method’s
input parameters (like $category
). To solve this, we must explicitly include the $category
parameter in the plugin’s method.
Plugin Setup: Step-by-Step
Step-1: Create the Plugin CategoryPlugin.php
file at
app/code/VendorName/ModuleName/Plugin
and add the following code:
An After Plugin lets us modify the method result. Here’s how you can write it.
<?php
namespace VendorName\ModuleName\Plugin;
use Magento\Catalog\Helper\Category;
use Psr\Log\LoggerInterface;
class CategoryPlugin
{
protected $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function afterGetCategoryUrl(Category $subject, $result, $category)
{
// Log for debugging
$this->logger->debug('Category Data:', ['category' => $category]);
// Add custom logic based on the $category object
if ($category instanceof \Magento\Catalog\Model\Category && $category->getIsActive()) {
$result = str_replace('old-url-part', 'new-url-part', $result);
}
return $result;
}
}
What’s Happening:
- Parameters:
$subject
is the original class,$result
is the method’s output, and$category
is the input parameter. - Logic: You can add custom conditions to check or modify the
$result
based on$category
. - Logging: Use logging to debug and verify the plugin is working as expected.
Step-2: Register the Plugin in di.xml
file at
app/code/VendorName/ModuleName/etc
and add the following code:
To activate the plugin, declare it in di.xml
.
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Catalog\Helper\Category">
<plugin name="category_plugin" type="VendorName\ModuleName\Plugin\CategoryPlugin" sortOrder="10" />
</type>
</config>
When to Use After Plugins
Use an After Plugin When:
- You only need to change the method result.
- You don’t need to modify the method’s logic or behavior.
Best Practices
- Keep Plugins Simple: Avoid adding too much logic to a plugin; it can make debugging difficult.
- Log Changes: Use logging to test and verify that the plugin is working as intended.
- Use Preferences for Major Changes: If you’re changing the core behavior significantly, consider using a preference instead of a plugin.
Example Scenario: Modify Category URLs
Let’s say you want to modify category URLs so that categories marked as active have a custom segment in the URL.
if ($category instanceof \Magento\Catalog\Model\Category && $category->getIsActive()) {
$result = str_replace('old-segment', 'new-segment', $result);
}
This customization ensures only active categories have the updated URL format.
Conclusion
Plugins are a powerful tool in Magento 2 to modify functionality without touching core files. For our example,
an After Plugin works well to modify the result of getCategoryUrl()
based on specific conditions.
Always follow best practices to keep your code maintainable and easy to debug.
By following this guide, you can easily use an After Plugin in Magento 2 to make changes like updating category URLs without changing the core code. Keep your site flexible and your code clean. For more simple tips and tricks about Magento, keep reading our blog!
0 Comments