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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace Module_Namespace\Module_Name\Helper; use \Magento\Framework\App\Helper\AbstractHelper; class Data extends AbstractHelper { public function HelperFunctionOne() { return "Yea, it works !!"; } } ?> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace Module_Namespace\Module_Name\Helper; use \Magento\Framework\App\Helper\AbstractHelper; class Data extends AbstractHelper { public function HelperFunctionOne() { return "Yea, it works !!"; } } ?> |
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.
1 |
echo $this->helper('Module_Namespace\Module_Name\Helper\Data')->HelperFunctionOne(); |
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 🙂
Leave a Reply