I was wondering if there was still no way to work with fake or generated (virtual?) properties in Doctrine?
I take an old example: a Person entity with a firstname and a lastname (based on a table with these two fields only).
Is it possible to create a virtual property fullName which would not be linked to any column in the table and which could be accessible without calling a handmade getFullName?
I obviously don't want to have to do it myself with the QueryBuilder.
/**
* @ORM\Column(name="LASTNAME", type="string", length=100, nullable=true)
*/
private $lastname;
/**
* @ORM\Column(name="FIRSTNAME", type="string", length=100, nullable=true)
*/
private $firstname;
/**
* @ORM\Column(type="string")
*/
private string $fullName = "";
public function __construct()
{
$this->fullName = $this->firstname . " " . $this->firstname;
}
I just came across this question on a slightly different subject... but it includes the solution to my issue.
It's actually enough to add an @ORM\HasLifecycleCallbacks on the Person entity and add an @ORM\PostLoad() on the virtual property (unmapped) init function.
Here is the final working solution:
/**
* Person
*
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Person
{
/**
* @ORM\Column(name="LASTNAME", type="string")
*/
private $lastname;
/**
* @ORM\Column(name="FIRSTNAME", type="string")
*/
private $firstname;
//Non mapped property
private $fullName;
/**
* @ORM\PostLoad()
*/
public function initFullName()
{
$this->fullName = $this->lastname . ' ' . $this->firstname;
}
}