PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 9, 2022

[FIXED] What is the difference between the serializer virtualProperty and the accessor?

 November 09, 2022     jms-serializer, jmsserializerbundle, php, serialization, symfony     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing