如何将id变量传递给具有依赖项注入Symfony 3.4的类

时间:2019-06-26 18:29:01

标签: symfony dependency-injection

我有一个使用依赖注入的类,还有另外两个类,可以正常工作。但是我想在控制器中实例化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();

1 个答案:

答案 0 :(得分:4)

如果该类对容器中没有的东西有依赖性,则该类不能从容器中加载。

要么自己在控制器中传递依赖项,要么

//open the box, that surrounds the messages
echo("<div class='dialogueBox'>");

while($row = mysqli_fetch_row($erg)) {
    //determine if the message is your own
    if($row[0] != $_SESSION["username"]) $ownmess = false;
    else                                 $ownmess = true;

    //begin div dependend on the sender of the message
    if($ownmess) echo ("<div class='dialogue own' >");
    else         echo ("<div class='dialogue other'>");

    //write Text
    echo($row[3] . "<br>");

    //write the timestamp as 'little' text (write blue, if it was read and its your own message)
    echo("<a class='little'");
        if($row[4] != 0 && $ownmess) echo(" style='color:Blue;'");
    echo(">" . $row[2]."</a>");

    //close div, and end message
    echo("</div> <br><br><br>");

}


//close big div, that surrounds all messages
echo("<br></div>");

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

.dialogueBox {
    width: 50%;
    margin-left: 25%;
    border: 1px solid Black;
    background-color: #BBAA88;  
    max-height: 500px;
    overflow: auto;
}

.dialogue {
    border: none;
    margin: 5px;
    border-radius: 5px;
    padding: 3px;
    font-size: 15;
    white-space: pre-wrap;
}

.own {
    float: right;
    background-color: #9aaa63;
}

.other {
    float: left;
    background-color: #cec178;
}

.little {
    font-size: 10px;
}

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

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