1

I am learning how to use dependency injections to get the classes I need.

The following will work when creating a controller.

...
use Magento\Framework\App\Action\Context;

class Index extends \Magento\Framework\App\Action\Action
{

  protected $_resultJsonFactory;
  protected $_directoryList;

  public function __construct(
    Context $context,
    \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
    \Magento\Framework\App\Filesystem\DirectoryList $directoryList
    )
  {
    $this->_resultJsonFactory = $resultJsonFactory;
    $this->_directoryList = $directoryList;
    parent::__construct($context);
  }
...

It can inject the dependencies I need. and I can then later use $this->_directoryList as needed.

I have tried to do the same for a helper class which needs access to this

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

  protected $_directoryList;

  public function __construct(
    \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
    )
  {
    $this->_directoryList = $directoryList;
    parent::__construct();
  }
...

Whenever I add a constructor I start receiving 500 errors on any page that tries to call this helper.

Is there a proper method or way to inject dependencies into a helper class.

2

Create function getMediaPath() in helper and use this function in other files

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

    protected $_directoryList;

    public function __construct
    (
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList
    ) {
        $this->_directoryList = $directoryList;
        parent::__construct($context);
    }

    public function getMediaPath()
    {
        return $this->directory_list->getPath('media');
    }
}
| improve this answer | |
1

The issue error 500 was given by your helper constructor, where it calls parent::construct() without object.

Here parent is \Magento\Framework\App\Helper\AbstractHelper and its construct method needs \Magento\Framework\App\Helper\Context object.

So, to fix it just change your helper constructor to

public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Framework\App\Filesystem\DirectoryList $directoryList
) {
    $this->_directoryList = $directoryList;
    parent::__construct($context);
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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