Issue
Per the Serializer virtualProperty documentation
Note: This only works for serialization and is completely ignored during deserialization.
Other than this limitation, what is the difference between using a virtualProperty and an accessor?
If nothing, why would one want to use it, as the accessor does not have this limitation.
Solution
Best explanations have a concrete example for illustrational purposes. Therefore I'll try to give an example for using both virtualProperty
and accessor
to show their differences.
We have an entity Person
, it has many different properties. One of them is birthdate
. Let's see the example:
class Person
{
/**
* @Accessor(getter="getFormattedBirthdate", setter="setBirthdate")
*/
private $birthdate;
public function setBirthdate(\DateTimeInterface $birthdate): self
{
$this->birthdate = $birthdate;
return $this;
}
public function getBirthdate(): \DateTimeInterface
{
return $this->birthdate;
}
public function getFormattedBirthdate(): string
{
return $this->birthdate->format('j F Y');
}
/**
* @VirtualProperty()
*/
public function getAge(): int
{
$today = new \DateTime('today');
$age = $today->diff($this->birthdate);
return $age->y;
}
}
We use the Accessor to specify which getter and setter method will be used during serialization and deserialization respectively. Per default getBirthdate
and setBirthdate
would have been used. We'd like however to use getFormattedBirthdate
for serialization.
The VirtualProperty helps us to display the calculated age. It will be used during serialization. Because it's not a real property, it has no setter and it makes no sense to deserialize it.
I hope the example helps to understand the difference between Accessor and VirtualProperty.
Answered By - cezar Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.