David Declercq
David Declercq

Reputation: 71

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

Upvotes: 0

Views: 67

Answers (1)

Amine Matmati
Amine Matmati

Reputation: 283

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;
}

Upvotes: 1

Related Questions