0

我尝试从模块 A 调用一个函数到模块 B 这里是模块 A 代码

namespace A\Epayment\Model;
  class Etransactions
    {
      public function customPayment{
        return "test";
      }

和模块 b 代码

  namespace B\Payment\Controller\Index;

class Payment extends \Magento\Framework\App\Action\Action
{
    protected $_pageFactory;
    protected $_transaction;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory,
        \ETransactions\Epayment\Model\Etransactions $transaction
    )
    {
        $this->_pageFactory = $pageFactory;
        $this->_transaction = $transaction;
        parent::__construct($context);
    }

    public function execute()
    {
        echo "Hello World".PHP_EOL;
        $foo="a";
        echo $foo;
        echo $this->_transaction->customPayment();
        //echo $this->customPayment();
        echo $foo;

        exit;
    }
}

此代码返回“hello world”,第一个 $foo,而不是第二个,并且不显示任何错误

有人可以解释我的错误在哪里吗?

编辑:我没有改变任何东西,但它现在工作正常。无论如何,感谢您的回答

4

2 回答 2

0

在 Magento 中,Helper 类可以在任何地方使用(块、控制器、模型、观察者、视图)。所以你应该在帮助类中创建一个方法,并通过以下方式在任何地方调用它。

声明辅助类和方法: ModuleA\Epayment\Helper\Data .

<?php
namespace ModuleA\Epayment\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function yourHelperMethod()
    {
        # code...
    }
}

调用方法:

$helper = $this->_objectManager->create(ModuleA\Epayment\Helper\Data::class);
$helper->yourHelperMethod();

注意:如果对象管理器没有注入你的类。请按照以下步骤操作:

1) 申报私有财产:

private $_objectManager;

2)注入构造函数进行初始化:

public function __construct(
    \Magento\Framework\ObjectManagerInterface $objectmanager
) {
    $this->_objectManager = $objectmanager;
}

3)在某些方法中使用:

public function someMethod() {
    $helper = $this->_objectManager->create(ModuleA\Epayment\Helper\Data::class);
    $helper->yourHelperMethod();
}
于 2019-07-25T08:03:51.817 回答
0

您要创建注入路径的对象不正确。

 public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory,
        \A\Epayment\Model\Etransactions $transaction // changes are here
    )
    {
        $this->_pageFactory = $pageFactory;
        $this->_transaction = $transaction;
        parent::__construct($context);
    }

请使用异常处理。

try{
$this->_transaction->customPayment();
}catch(Exception $e){
//log your exception here.
}
于 2019-07-25T02:03:44.470 回答