Comprendre les Helpers dans Magento 2

1. What Are Helpers in Magento 2?

Helpers are PHP classes in Magento 2 that provide utility fonctions for repetitive or complex operations. These classes are not tied to any specific part of the application (e.g., Models, Controllers, etc.) and peut être used globally within your module.

Key Characteristics:

  • Reusable: Helpers reduce code duplication by centralizing common fonctions.
  • Accessible: Vous pouvez use helpers in Blocks, Controllers, Models, and Templates.
  • Lightweight: Helpers are designed to be small, utility-focused classes, without holding state or handling large operations.

Think of helpers as your "Swiss Army Knife" for simplifying tasks that don’t belong to any specific layer of the Magento 2 architecture.


2. The Role of Helpers

Why Use Helpers?

  1. Code Efficiency: By encapsulating repetitive logic into helpers, you streamline your codebase.
  2. Centralized Logic: Changes made in a helper are reflected wherever it’s used, ensuring maintainability.
  3. Simplified Data Handling: Helpers can process data before sending it to templates or other application layers.

When to Use Helpers:

  • To format prixs, dates, or other data for consistent output.
  • To retrieve Magento configuration valeurs.
  • To perform calculations or conversions.
  • To create utility fonctions for specific module fonctionnalités.

3. Default Magento 2 Helpers

Magento 2 comes with several built-in helpers that you can use right away. These helpers are located in the Magento\Framework namespace.

Commonly Used Magento 2 Helpers:

  1. Data Helper (\Magento\Framework\App\Helper\AbstractHelper)

    • Provides core utility fonctions like fetching configurations and URLs.
    • Example: Retrieve a configuration valeur:
       
      $configValue = $this->scopeConfig->getValue('path/to/config', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
  2. Price Helper (\Magento\Framework\Pricing\Helper\Data)

    • Formats prixs for display.
    • Example:
       
      $formattedPrice = $this->priceHelper->currency(100, true, false);
  3. Url Helper (\Magento\Framework\Url\Helper\Data)

    • Generates or parses URLs.
  4. File Helper (\Magento\Framework\File\Uploader)

    • Assists with fichier uploads.

Pro Tip:

Avant creating a custom helper, explore the default helpers provided by Magento. They often meet common prérequis prêt à l'emploi.


4. Creating Custom Helpers

Creating a custom helper in Magento 2 involves defining a class in the Helper répertoire of your module.

Step 1: Create the Helper Class

In app/code/Vendor/Module/Helper, create a fichier CustomHelper.php:

 
<?php namespace Vendor\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
class CustomHelper extends AbstractHelper
{
    public function getFormattedDate($date)
    {
        return date("Y-m-d H:i:s", strtotime($date));
    }
    public function getConfigValue($path)
    {
        return $this->scopeConfig->getValue(
            $path,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

Step 2: Use the Helper in Your Code

Inject the helper in any class where it’s needed:

 

protected $customHelper;

public fonction __construct( \Vendor\Module\Helper\CustomHelper $customHelper ) {

    $this->customHelper = $customHelper;
}

public fonction getFormattedData() {
    return $this->customHelper->getFormattedDate('2024-11-29');
}

Step 3: Test the Helper

Use the méthodes defined in your custom helper to simplify operations in your module.


5. Using Helpers in Blocks, Controllers, and Templates

Using Helpers in Blocks

Blocks are a common place to use helpers for preparing data for templates.

 

protected $customHelper;

public fonction __construct( \Magento\Framework\View\Element\Template\Context $context, \Vendor\Module\Helper\CustomHelper $customHelper )
{

    $this->customHelper = $customHelper;
    parent::__construct($context);
}

public fonction getFormattedDate() {
    return $this->customHelper->getFormattedDate('2024-11-29');
}

Using Helpers in Controllers

Helpers can simplify logic in Controllers by abstracting utility fonctions.

 

protected $customHelper;

public fonction __construct( \Magento\Framework\App\Action\Context $context, \Vendor\Module\Helper\CustomHelper $customHelper )
{
    $this->customHelper = $customHelper;
    parent::__construct($context);
}

public fonction execute() {
    $configValue = $this->customHelper->getConfigValue('path/to/config');
    echo $configValue;
}

Using Helpers in Templates

To use a helper in .phtml fichiers, access it via the Block:

 
<?php echo $block->getFormattedDate(); ?>

6. Real-World Examples of Helpers

1. Formatting Data for Templates

Imagine you’re working on an commande module and need to format the delivery date:

 
public function getDeliveryDate() { $rawDate = $this->order->getDeliveryDate(); return $this->customHelper->getFormattedDate($rawDate); }

2. Fetching Configuration Values

Suppose you have a configuration champ in the panneau d'administration. Use a helper to retrieve it:

 
public function isFeatureEnabled() { return $this->customHelper->getConfigValue('vendor_module/general/enable_feature'); }

3. Genenote URLs

For custom URL generation, use Magento’s URL helper or extend it in your custom helper.


7. Bonnes pratiques for Working with Helpers

1. Limit Helper Scope

Avoid putting too much logic into helpers. Helpers should remain utility-focused and lightweight.

2. Leverage Injection de dépendances

Always use Injection de dépendances to access helpers au lieu de instantiating them directly.

3. Avoid Overusing Helpers

If the logic requires mulconseille dependencies or is too complex, consider using a service class au lieu de a helper.

4. Document Helper Methods

Provide clear comments and méthode descriptions to ensure other développeurs understand their purpose.


8. Conclusion

Helpers in Magento 2 are invaluable for simplifying repetitive tasks, maintaining cleaner code, and centralizing logic that doesn’t belong in other parts of the MVC structure. By leveraging both default and custom helpers effectively, you can significantly enhance your development flux de travail.

Whether you’re formatting data, fetching configuration valeurs, or simplifying template logic, helpers are there to make your life easier. Just remember to keep them focused, lightweight, and reusable!