0

I am trying to create a module with a helper file where I declare functions I can use within my module

I have the module working and I have a helper file at :

Modzinc/Adminmonitor/Helper/Data.php


<?php

namespace Modzinc\Adminmonitor\Helper;

use Magento\Framework\App\Helper\AbstractHelper;


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

{

public function successMessage()
{
    return "My messgae here";
}
}

I have a page at Modzinc/Adminmonitor/Adminsuccess.php which is called everytime there is a successful admin login and that all works great the event fires and an email is sent. But when I try and get the message I have declared in my helper I get an error message :

Undefined property: Modzinc\Adminmonitor\Observer\AdminSuccess::$helper in ........../app/code/Modzinc/Adminmonitor/Observer/AdminSuccess.php on line 14

Here is my code for AdminSuccess.php

<?php
namespace Modzinc\Adminmonitor\Observer;

use Magento\Framework\Event\ObserverInterface;
use Modzinc\Adminmonitor\Helper\Data;
use Magento\Framework\Event\Observer;

class AdminSuccess implements ObserverInterface {



public function execute( Observer $observer ) {

    $successMessage = $this->helper->successMessage();
    mail('[email protected]','login Successful',$successMessage );

} 
}

I am pretty certain my helper is set up correctly but my question is how do you use it in other files within my module. I know I can just declare the function in the same file but I would want to learn how to use it from the helper File as my intention is to keep most of my functions in the helper file as They will be reused throughout my modules files.

Any help would be great

1 Answer 1

0

You did not initialise you helper properly. Instead using $successMessage = $this->helper->successMessage();

\Modzinc\Adminmonitor\Helper::successMessage();

Call this line in any place, it should call you helper successMessage function.

If you really want to use something like $this->helper. try add these code before you observer excute():

public function __construct(
        \Modzinc\Adminmonitor\Helper $helper
) {
     $this->helper = $helper;
}

Then you can just call $this->helper->successMessage();

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.