简体   繁体   中英

Symfony2 - Update an entity when updating another entity

This question is more related to code organization (following Symfony 2 guidelines/style) than to the code itself.

My problem is easy and common: I have two related entities, Account and Lines. In the Account entity, I have one field called CurrentTotal, and in the Lines entity, a field called Amount.

What I need is to update the Account.CurrentTotal field when I persist or update any Lines entity, adding or substracting the Amount quantity.

I know that I can add this business logic to the controller, but doing this I'm coupling very much the controller to the entities, and I think that this isn't a good place to put business logic.

I can also create a Doctrine listener, and when I update or persist an entity of the type Line, update the related Account entity. But if I have a hundred entities, and I need fifty or sixty of this "triggers", maybe this will be a mess...

And my question is: Which is the correct/recommended way of building this kind of "triggers" with Symfony 2? Keep in mind that I need this to be testable with PHPUnit, so it must be loose-coupled.

Asuming you use doctrine and have a relation between Account and Lines and have mapped this relationship. If you have not, look at this .

I would add a method called countTotal() to Account which calculates the total en sets it to its field. In Lines there must be a method setAmounts or something where I would call countTotal()

Simple code example:

class Account(){
    private $total;
    protected arrayCollection $lines;//your lines

    //some basic methods
    public function getLines(){};
    public function setLines(lines){};
    public function addLine(line){};
    public function getTotal(){};

    public function countTotal(){
        $total = 0;
        foreach(line in $this->lines){
            total += lines;
        }
        $this->total = total;
    }
}

class Line(){
    private $amount
    protected $account

    public function setAmount(amount){
        $this->amount = amount;
        $this->account->countTotal();
    }

    public function getAmount(){};

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM