0

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

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I thought that the constructor of Commande was called just once, when service is called for the first time. I mean, if it is the same instance of Commande object, why constructor would be called each time ?
Well it is not a singleton, you're not getting the same instance of a class, you're getting a new instance each time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.