semsem
semsem

Reputation: 1192

FosRestBundle: Dynamic VirtualProperties

In FOSRestBundle : Annotations, I want to use multiple @VirtualProperty with dynamic names because i fetch the properties names from the database (unknown number of properties)

class User
{
   private $id;
   private $name;

   /**
    * @Serializer\VirtualProperty
    *
    * @return array
    */
   public function getSomeMethod()
   {
       return array('property_name1'=> 'value1', 'property_name2'=>'value2');
   }
}

Where property_name1 & property_name2 .. property_name3 .. etc are dynamic with infinit number

I want to set them as virtual properties , each property has a string value.

I don't want to set them as array with one property.

If there is no way to do this, please let me know if i can do the same task from the controller?

Upvotes: 1

Views: 195

Answers (2)

qooplmao
qooplmao

Reputation: 17759

Originally a comment...

You might be able to do this using @Serializer\Inline so that the properties of the array of bought up to be properties of the the parent object.

Some more info

This essentially allows you to have the exposed properties or keys/value of and array or object to be bought up to be properties of the parent object.

For example..

class Id
{
    /**
     * @Expose
     */
    private $id;

    //...
}

class Parent
{
    /**
     * @Expose
     * @Inline
     */
    private $id;

    /**
     * @Expose
     * @Inline
     */
    private $name = 'parent';

    /**
     * @Expose
     * @Inline
     */
    private [
        'key' => 'value',
    ];

    public function __construct()
    {
        $this->id = new Id('an-id');
    }
}

Would first be transformed to an array similar to the following during serialization

[
    'id' => 'an-id',
    'name' => 'parent',
    'key' => 'value',
]

Upvotes: 1

martin
martin

Reputation: 96889

Since FOSRestBundle uses JMSSerializer underneath and you want to be able to have full control of what the serializer returns and the output data strongly depend on the input it receives you can write a custom handler for one particular class.

For more detail info see:

Upvotes: 1

Related Questions