首页 > 解决方案 > 如何将 id 变量传递给具有依赖注入 Symfony 3.4 的类

问题描述

我有一个使用依赖注入的类,还有另外两个类,这很好用。但是我想在控制器中实例化 Merchant 类并传递一个 id 。我没有得到的是构造函数期望更多的值'CurrencyConverter'和'TransactionTable'那么我该如何完成代码??,我不需要通过。所以我不清楚如何使它工作,谢谢

模型类

namespace TransactionBundle\Model;

class Merchant
{
public $_transactions;
public $_currencyConverter;
public $_id;

public function __construct($id,CurrencyConverter                    
    $currencyConverter,TransactionTable $transactions)
{
    $this->_transactions = $transactions;
    $this->_currencyConverter = $currencyConverter;
    $this->_id = $id;

}

public function getTransactions() {

    $this->_currencyConverter->convert();

    $this->_transactions->getData();       

}

}

trying to instantiate in the controller

$merchant = new Merchant(2,?,?);

$results = $merchant->getTransactions();

标签: symfonydependency-injection

解决方案


如果该类依赖于容器中不存在的东西,则无法从容器中加载该类。

在控制器中自己传递依赖项:

$merchant = new Merchant(2, $currencyConverter, $transactions);

或者在容器中使用工厂服务:

class MerchantFactory {
    private $currencyConverter;
    private $transactions;

    // constructor omitted for brevity

    public function getMerchantForId($id) {
        return new Merchant($id, $this->currencyConverter, $this->transactions);
    }
}

然后在您的控制器中,取决于工厂:

$merchant = $this->merchantFactory->getMerchantForId(2);

推荐阅读