How To Create And Use Helpers In Magento 2


What is Helper ?

Helpers are classes with collection of classes that allows us to perform common functionalities and features that can be accessed throughout Magento site.

Helper functions can be accessed from controllers, views, models, templates where common functionality is to be obtained. For eg we can create a helper class in order to create logs in web application. Hence, considered to be a helpful tool to Magento developer like you 🙂

I believe everyone is good in creating a simple module structure. So, let us dive only with helper.

Create a Helper folder inside your module directory. Inside Helper folder create a file called Data.php where all your helper functions are written.

The above code creates helper where you can add as much functions for different functionality. I have created a function HelperFunctionOne which can be called throughout your website using dependency injection.

In any classes :

In template :

The template engine for Magento 2 has a method helper() which can create helper instance in any templates. Using this instance we can inject our helper class and call our helper function.

Conclusion :

We finally created helper functions and accessed through classes and templates in Magento 2. I hope the basic concept of Helper is understood to everyone. If you have any queries regarding helper functionalites drop your message in comment box.

Find the complete working code at github

Hope it helps you !
happy Coding 🙂

Comment!

Leave a Reply

Your email address will not be published. Required fields are marked *