Sunday, June 1, 2025

Extend core & 3rd-party using Plugins

🔧 Magento 2 Plugins: Before, After, and Around Explained (with Real Use Cases)

Magento 2 plugins, also known as interceptors, are a powerful way to customize and extend core functionality without overriding original classes. If you're building custom features or tweaking existing behavior, understanding Before, After, and Around plugins is a must.

🧩 What Are Magento 2 Plugins?

Plugins in Magento 2 allow you to intercept method calls at three key points:

  • Before: Run custom code before the original method.
  • After: Run code after the original method and optionally modify its return value.
  • Around: Take full control over the method execution.

🛠 Code Examples

Let’s say you want to modify the behavior of the getFinalPrice() method in a product class.

🟨 Before Plugin

public function beforeGetFinalPrice(\Magento\Catalog\Model\Product $subject, $qty) {
    return [$qty + 1]; // Modify argument
}

🟩 After Plugin

public function afterGetFinalPrice(\Magento\Catalog\Model\Product $subject, $result) {
    return $result * 0.9; // Apply 10% discount
}

🟥 Around Plugin

public function aroundGetFinalPrice(\Magento\Catalog\Model\Product $subject, callable $proceed, $qty) {
    if ($subject->getTypeId() == 'virtual') {
      return 0; // Skip method
    }
    return $proceed($qty);
}

✅ When to Use Plugins

  • Before: Modify method input (e.g. price, quantity)
  • After: Tweak returned data (e.g. formatted output, discounts)
  • Around: Override behavior, apply conditions, or stop execution

❌ When Not to Use Plugins

  • Avoid using with constructors or final/private/static methods
  • Don’t use Around plugins excessively—they can increase complexity and performance overhead
  • For simple behavior tracking, use observers instead

🔍 How to Find Which Plugins Are Used

Use this CLI command:

bin/magento dev:di:info Magento\Catalog\Model\Product | grep Plugin

Or, if you want full visibility, inspect::

  • generated/metadata/
  • generated/code/
  • di.xml entries for <type name="ClassName">

💡 Recommended Plugin Practices

Do Don't
Use DI and type-safe arguments Overuse Around plugins
Add PHPUnit tests for each plugin Modify constructor logic
Name plugins clearly (e.g., ApplyDiscountPlugin) Skip docblocks and comments
Keep logic concise and focused Use many plugins on the same method

🏆 Recommended Plugin Tools

  • 🔌 MagentoWizard (VS Code plugin): Auto-generate plugins quickly
  • 📦 Mage2Gen: Plugin scaffolding with XML support
  • 🚫 Avoid: Poorly maintained or unverified third-party plugins

🚀 Final Thoughts

Magento plugins are incredibly flexible—but with great power comes great responsibility. Use Before and After wisely, and save Around for when it’s truly necessary. And always write clean, well-tested, documented code. Your future self will thank you! 🙌