5

All of the tutorials I'm looking at pretty much say the same thing. To add a helper, just add the following code:

<?php

namespace YourName\YourModule\Helper;

class ClassName extends \Magento\Framework\App\Helper\AbstractHelper
{

...

}

It seems to be required in all of the tutorials, but no one explains it. It also seems to work exactly the same if I remove it (though, my custom module is not quite as complicated as others).

Can any experts offer some insight?

4

Your custom class don't need to extends the Abstract helper core class.

However, the Abstract helper provides helpful methods:

  • Module statuses manager - Magento\Framework\Module\Manager
  • Logger - Magento\Framework\Logger\Monolog
  • Http request info - Magento\Framework\App\Request\Http
  • Url - Magento\Framework\Url.
  • Library for working with HTTP headers - Magento\Framework\HTTP\Header
  • Event manager - \Magento\Framework\Event\Manager.
  • Library for working with client ip address -\Magento\Framework\HTTP\PhpEnvironment\RemoteAddress.
  • Cache configuration model. Provides cache configuration data to the application - Magento\Framework\Cache\Config.
  • Base64 encoder and decoder for URLs - Magento\Framework\Url\Encoder and Magento\Framework\Url\Decoder.
  • Application configuration object. Used to access configuration when application is initialized and installed - Magento\Framework\App\Config

If you want to use some helpful methods, your custom class should extends from the Abstract helper.

1

If you want to access the helper in templates using $block->helper(HelperClassName::class), Magento will only allow it if the class extends AbstractHelper.

But this is not a recommended practice anyways, see: Magento 2: proper use of helpers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.