photo credit: Red alert -[ HMM ]- via photopin (license)

Creating helpers in Magento 2

Tags: ,

We all know them from Magento 1: Helpers. Those (mostly) tiny little classes that gave us functionality for various things throughout our site. Needless to say, Magento 2 also has those helpers. In this article I’ll explain to you how to create and use helpers in your project.
Please note that we use the boilerplate module from the article ‘Creating a module in Magento 2‘ as the entry point for this article.

The Helper class

Creating a helper is actually very simple. Inside your module, create a folder called Helper , and inside this folder place a file called Data.php :

This is a tiny class with a single function: doSomething() . In constrast with Magento 1, we don’t need to declare our helpers in a config.xml  file or something. Magento 2 can locate it’s helpers on it’s own.

How can we use it?

Now we’ve got our helper, we also want to use it. This can be done in various ways:

In templates

The default template engine in Magento 2 that is responsible for rendering the templates is Magento\Framework\View\TemplateEngine\Php . This has a default method called helper()  which you can use to create a helper instance inside your template:

In other classes

In other classes, like blocks or models, you can simply use the Constructor Injection provided by Magento 2 to create an instance of your helper when your class is instantiated:

This post is part of the series Magento 2 Development from Scratch.

Visitors give this article an average rating of 4.6 out of 5.

How would you rate this article?

One thought on “Creating helpers in Magento 2”

  1. arnold says:

    Missclicked – Please change Vote from 3/5 to 5/5 – very helpfull article, thanks a log 🙂

Leave a Reply