symfony - 如何将 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();
解决方案
如果该类依赖于容器中不存在的东西,则无法从容器中加载该类。
在控制器中自己传递依赖项:
$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);
推荐阅读
- python - 如何使用类列表作为函数参数?
- python - Python - Slate3k 安装 pdfminer 后给我一个类型错误
- javascript - 如何用正则表达式杀死 tabindex="*" 并在 Javascript 中全部替换
- javascript - 如何在运行第二个函数javascript之前等待第一个函数完成
- python-3.x - 如何从 UCI 机器学习存储库将数据集(.data 和 .names)直接读入 Python DataFrame
- angular - PrimeNg- 悬停时的 p 下拉工具提示
- javascript - javascript从数组中读取对象
- django - Django 尝试使用现有主键保存对象
- filter - 卡尔曼滤波器实现在高冲击和加速度下使用 IMU 估计位置
- python-3.x - python只返回值