skip to Main Content

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.

/**
* @ORMColumn(name="LASTNAME", type="string", length=100, nullable=true)
*/
private $lastname;
    
/**
* @ORMColumn(name="FIRSTNAME", type="string", length=100, nullable=true)
*/
private $firstname;
    
/**
* @ORMColumn(type="string")
*/
private string $fullName = "";
    
public function __construct()
{
    $this->fullName = $this->firstname . " " . $this->firstname;
}

2

Answers


  1. Chosen as BEST ANSWER

    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 @ORMHasLifecycleCallbacks on the Person entity and add an @ORMPostLoad() on the virtual property (unmapped) init function.

    Here is the final working solution:

    /**
     * Person
     *
     * @ORMEntity
     * @ORMHasLifecycleCallbacks
     */
    class Person
    {
    
        /**
         * @ORMColumn(name="LASTNAME", type="string")
         */
        private $lastname;
    
        /**
         * @ORMColumn(name="FIRSTNAME", type="string")
         */
        private $firstname;
    
        //Non mapped property
        private $fullName;
    
        /**
         * @ORMPostLoad()
         */
        public function initFullName()
        {
            $this->fullName = $this->lastname . ' ' . $this->firstname;
        }
    }
    

  2. For those using JMS Serializer, you can also use @VirtualProprety annotation.

    /**
    * Get full name (constists of lastname + space + firstname).
    *
    * @SerializerVirtualProperty()
    * @SerializerType("string")
    * @SerializerSerializedName("fullName")
    * @return string|null
    */
        
    public function getFullName()
    {
        return $this->lastname . ' ' . $this->firstname;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search