0

In Magento 1, I can have return Mage::helper('core') which is object of Mage_Core_Helper_Data. I wonder what the equivalent class for Magento 2.

2 Answers 2

0

I think I figured it out. In Magento 2, the Helper class can be defined as

    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
        public function __construct(
          \Magento\Framework\App\Helper\Context $context
     ){
           parent::__construct($context);
      }
    }

If you want to get Mage::helper('core'), then you just define a public function in this class,

    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
       public function __construct(
         \Magento\Framework\App\Helper\Context $context
       ){
          parent::__construct($context);
       }

       public function getCoreHelper()
       {
          return $this;
       } 
    }

If you want to get "Mage::helper('core/helper')" like in Magento 1, you just need to use the automatic constructor dependency injection:

    class Data extends \Magento\Framework\App\Helper\AbstractHelper
    {
       protected $httpHelper;

       public function __construct(
          \Magento\Framework\App\Helper\Context $context,
          \Magento\Framework\App\Http $httpHelper
       ){
          parent::__construct($context);
          $this->httpHelper = $httpHelper;
       }

       public function getCoreHelper()
       {
          return $this;
       } 
       public function getHttpHelper()
       {
          return $this->httpHelper;
       }
    }
0

If you wanting to know which helper class to extend from in order to create your own helper class, it is: \Magento\Framework\App\Helper\AbstractHelper.

3
  • Thank you so much. I have this question because I have been rewriting some M1 modules to M2. In M1, there are some codes just directly uses Mage::helper('core') and Mage::helper('core/http') to implement some functionalities.
    – Jeff Yu
    Commented Jul 30, 2018 at 23:12
  • My pleasure. In Magento 2, they have done a much better job of sticking to the Single-Responsibility doctrine. Essentially, each php class has one job. Bc of this, you will find yourself instantiating many more classes as needed. Additionally, since you are in the process of converting modules, you should read about Composition over Inheritance. In layman's terms, try to stay away from abstraction as much as possible. Become familiar with that now and it will benefit you throughout your career. Commented Jul 30, 2018 at 23:16
  • @JeffYu please don’t forget to mark this answer as accepted if you feel it satisfactorily answered your question. Thanks! Commented Jul 31, 2018 at 6:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.