I have an entity that needs to return an instance of another entity – the stored record or a new one if one has not been stored.
<?php
/**
* @Entity
*/
class User {
/**
* @OneToOne(targetEntity="Basket")
* @JoinColumn(nullable=true)
*/
protected $activeBasket;
public function getActiveBasket() {
if (!isset($this->activeBasket)) {
$this->activeBasket = new Basket($this);
// $em->persist($this->activeBasket);
// $em->flush();
}
return $this->activeBasket;
}
}
My problem is that I don’t have an EntityManager to use to persist this new Basket (and obviously don’t want one in the Model). I’m not sure as to the best way to do this. I do want to be able to call $user->getActiveBasket() and retrieve a basket, whether it’s previously created or a new one.
It feels like this should be a common problem, or that there’s a better way to structure this (I’m hoping there’s a way to hook one in in an EntityRepository or something). How can I do this?
I wouldn’t return a
new Basket()when it is null or not set. The model (entity) should only serve for setting and getting its properties.The logic when
$user->getActiveBasket()returned null should be elsewhere – in controller or in entity’s reporitory object…So I would move
public function getActiveBasket() { ... }into justpublic function getActiveBasket() { return $this->activeBasket; }and somewhere in the controller I would do: