Magento – how can i call helper function of other module in the custom module

dependency-injectionmagento2module

I have two modules (amodule, bmodule) and want to use an existing logic of bmodule in my current module amodule

I tried to use dependency injection in constructor, but i got an error on during runtime, because the parameter needed was the helper of the other module, but given was none.

class NewAction extends \Magento\Newsletter\Controller\Subscriber\NewAction
{

    private $_bhelper;

    public function __construct(
        Context $context,
        SubscriberFactory $subscriberFactory,
        Session $customerSession,
        StoreManagerInterface $storeManager,
        CustomerUrl $customerUrl,
        CustomerAccountManagement $customerAccountManagement,
        \MyModule\bmodule\Helper\Data $bhelper
    )
    {

        $this->_bhelper = $bhelper;

        parent::__construct(
            $context,
            $subscriberFactory,
            $customerSession,
            $storeManager,
            $customerUrl,
            $customerAccountManagement
        );
    }

    ...
}

   [message] => Uncaught TypeError: Argument 7 passed to MyModules\amodule\Controller\NewAction::__construct() must be an instance of Mymodules\bmodule\Helper\Data, none given, called in 

How can i make a cross call of another module logic?

In magento1 it was simply

Mage::helper('bmodule')->doMyStuff();

How can i do this correctly in Magento2?

Best Answer

Delete var/generation/vendor/yourmodule folder

Magento 2 auto create Interceptor file for module's constructor class and after it check constructor class from Interceptor.php instead of your file.

Run this command

rm -rf var/generation/vendor/youmodule*

OR

rm -rf var/generation/*

Then flush cache

php bin/magento cache:flush