Magento 2 create  and use helper

Using helper you can put your methods in there that you have no idea where to put them. For example if you want create the thumbnail of image you use the helper method. The method you don’t know where to put put in helper class.

Now creating the helper and use of it.

Create Helper folder in module directory.



namespace QaisarSatti\HelloWorld\Helper

 

Now create the your helper class what name you want to put.In my case i will use Data file. Now the complete path will be.

namespace QaisarSatti\HelloWorld\Helper\Data.php



This file will be extend with.



 \Magento\Framework\App\Helper\AbstractHelper



Now create helper Data class.

 


<?php

/**

* Simple Hello World Module

*

* @category QaisarSatti

* @package QaisarSatti_HelloWorld

* @author Muhammad Qaisar Satti

* @Email qaisarssatti@gmail.com

*

*/


namespace QaisarSatti\HelloWorld\Helper;



use Magento\Store\Model\Store;



class Data extends \Magento\Framework\App\Helper\AbstractHelper

{



public function getTitle()

{

return  'First Hello World Module';

}

}

Now we will use helper method  in our block.

<?php

/**

* Simple Hello World Module

*

* @category QaisarSatti

* @package QaisarSatti_HelloWorld

* @author Muhammad Qaisar Satti

* @Email qaisarssatti@gmail.com

*

*/


namespace QaisarSatti\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template

{

protected $_helper;

public function __construct(

\QaisarSatti\HelloWorld\Helper\Data $_helper,

) {



$this->_helper=$_helper;



}

public function _prepareLayout()

{

parent::_prepareLayout();

$this->pageConfig->getTitle()->set($this->_helper->getTitle());

return $this;

}

}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

3 thoughts on “Magento 2 create  and use helper

  1. Many thanx for the code…can the code of helper method in block used in observer…
    Means that can observer calls the helper methods like the way mentioned for block….any help would be appriciated.

Leave a Reply