当前位置: 动力学知识库 > 问答 > 编程问答 >

Symfony2 : service and nested class

问题描述:

I have a class Commande and a class Panier.

The first one contains the second one as an attribute.

The first one is also defined as a service.

I want to use the same instance of my Commande object, but I also want to use the same instance of its Panier object.

Seems after my first tests than the Panier object is re-created each time; for example if I try to add some article in it the article is not saved.

Is there a special thing to do ? Do I have to define Panier class as a service also and inject it in the Command one ?

class Commande

{

/**

* @var integer

*

* @ORM\Column(name="id", type="integer")

* @ORM\Id

* @ORM\GeneratedValue(strategy="AUTO")

*/

private $id;

/**

* @Assert\Type(type="LeJardinEbene\Bundle\Entity\Panier")

*

* @ORM\OneToOne(targetEntity="LeJardinEbene\Bundle\Entity\Panier", inversedBy="commande")

* @ORM\JoinColumn(nullable=false)

*/

private $panier;

public function __construct() {

$this->setPanier(new Panier());

}

And the service :

commande:

class: LeJardinEbene\Bundle\Entity\Commande

tags:

- { name: commande, alias: commande }

And in my controller, here is how I get my Panier object :

$panier = $this->get('commande')->getPanier();

Thank you guys.

Regards

网友答案:

Well you're instantiating a new Panier() each time you're creating a Command so it's recreating it every time.

Try passing in the $panier as a constructor argument

public function __construct(Panier $panier) {
    $this->panier = $panier;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: