In Magento 2, helper is a class, which contains a collection of methods that perform common functions on objects and variables. It can be incredibly useful. If you are not sure about putting a method in the right place, you can use the helper. For instance, if you want to create an image thumbnail, you have to use helper method.
And the method that you are unsure to use is the helper class. In this article, you will find the way of creating a helper in Magento 2. But before discussing that, let’s know the reason for using the class in the platform.
Why Creating Magento 2 Helpers?
Magento 2 helpers are global elements. You can use them at any place. So, you get a complete freedom. Being available globally, they can be called everywhere in the platform. You just have to put them in the class. So, it is really easy to implement. You can also use them as single instances of objects, which are regarded as Singletons. If you have to create methods for the most common tasks, like building logs, there is no better way than using helpers in Magento 2.
Creating Magento 2 Helper
Step 1: Create a simple module in Magento 2. Here, you are assumed to know the process.
Step 2: Now, you have to create a file named Data.php in the Helper folder. Take a look at the structure stated below to have a clear idea.
<Module_Namespace>|-------- Module_Name/|---------------- composer.json|---------------- registration.php|---------------- etc/|------------------------ module.xml|---------------- Helper/|------------------------ Data.php
The directory structure of your module should be like that.
Step 3: Insert the lines in Data.php file:
<?phpnamespace Module_NamespaceModule_NameHelper;use MagentoFrameworkAppHelperAbstractHelper;class Data extends AbstractHelper{ public function RandomFunc() { echo "This is Helper in Magento 2"; }}
Now, you have got the helper. Here, you have built a method, called RandomFunc(). You can call it anywhere in Magento 2. Thanks to the Dependecy Injection, which allows the environment to build and provide you with the object, rather than forcing you to instantiate an object.
Step 4: Now, it’s time for using the helper. Just use the following codes:
<?phpuse Module_NamespaceModule_NameHelperData;class RandomClass{ public function __construct(Data $helper) { $this->helper = $helper; } public function func() { $this->helper->RandomFunc(); }}
Here, in the constructor of RandomClass, an object of Data class ($helper) has been created automatically. This concept is known as Dependency Injection.
Conclusion
In this article, you have learned to create and use Helper in Magento 2. You can call it from anywhere, including model and controller, in the platform. You can also call it from another Helper class as well. So, by using Helper, you can take the functionality to a whole new level in Magento 2.
Check out these top 3 Magento hosting services:
- Want to get top recommendations about best hosting? Just click this link!