Magento 2 Helpers

Magento 2 Helpers are utility classes used to store reusable functions that can be accessed throughout your module—commonly for formatting, retrieving configurations, or general-purpose logic.

📦 What is a Helper in Magento 2?

A Helper class in Magento 2 is used to store logic that doesn’t belong to a controller, model, or block. It’s best for:

  • Accessing system/store configuration values
  • String formatting or calculations
  • Reusable logic shared across the module

📁 Create a Custom Helper

Let’s create a helper that retrieves a configuration value.

Step 1: Create Helper File


<?php
namespace Vendor\Module\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\ScopeInterface;

class Data extends AbstractHelper
{
    const XML_PATH_MODULE = 'custom_section/general/';

    public function getConfigValue($field, $storeId = null)
    {
        return $this->scopeConfig->getValue(
            self::XML_PATH_MODULE . $field,
            ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }
}
  

Step 2: Define System Configuration

Add this configuration in system.xml if not already created:



    
    Magento\Config\Model\Config\Source\Yesno

  

Step 3: Use Helper in Your Code

Inject the helper in your controller, block, or model:

protected $helper;

public function __construct(
    \Vendor\Module\Helper\Data $helper
) {
    $this->helper = $helper;
}

// Usage
$isEnabled = $this->helper->getConfigValue('enable');
  

✅ Best Practices

  • Only use Helpers for reusable utility code
  • Keep logic lightweight—avoid business logic
  • Inject via dependency injection (avoid object manager)

🧠 Summary

  • Helpers are great for reusable methods
  • They are not meant to replace models or service classes
  • Common use: access configuration, formatting, utility methods