Magento 2 – Proper Use of Helpers

best practicehelpermagento-2.1magento2template

I'm starting to see more and more people declaring helpers classes in order to be able to use the following in the template files:

$this->helper('Path/To/Helper/Class')->customMethod();

This kind of code lets people avoid the do not use the object manager directly restriction but I tend to see code that should be block code in those helpers.

So here are my questions:

  • what should one write in the helper classes ?
  • in which cases is it relevant to use helper methods in the templates?

Best Answer

Don't.
This is like using ObjectManager::getInstance()->create() in a template!
Use a custom Block that receives the helper as a constructor dependency instead, and add a proxy method that calls the helper method.

In the template:

$block->customMethod()

In the block:

public function __construct(Path/To/Helper/Class $helperClass, ...other dependencies...)
{
    $this->helper = $helperClass;
    // ...other assignments and call to parent::__construct()
}

public function customMethod()
{
    return $this->helper->customMethod();
}

In OOP principle speak this avoids violating the "Law of Demeter". It encapsulates the business logic in the block instead of the template. As a side effect it also makes the logic more testable as the logic is moved into the block.

Regarding what logic put into the helper classes, I find that in Magento 2 helpers mostly make sense for services, like something that is not a model, but contains reusable code, for example price formatting (which is contained in the core, but I can't think of a better example right now).

Related Topic