0

I am working on a REST API with Symfony 5.4; PHP 7.4; using the default Symfony serializer. When I define a model extending from another, the properties of the child model are serialized before the parent's properties; I would like to change that behaviour.

Simple example: Say I have a model called DogDetails which extends from another model called Dog:

class Dog
{
    /**
     * @OA\Property(type="integer")
     * @var int
     */
    protected $dogId;

    public function __construct(int $dogId)
    {
        $this->dogId             = $dogId;
    }

    // ... Getters and setters
}

class DogDetails extends Dog
{
    /**
     * @OA\Property(type="string")
     * @var string
     */
    protected $color;

    public function __construct(int $dogId, string $color)
    {
        parent::__construct($dogId);
        $this->color        = $color;
    }

    // ... Getters and setters
}

Then if in my controller I simply output return new DogDetails(1, 'Brown'); the result is

{
    "color": "Brown",
    "dogId": 1
}

and I would like to obtain the other ordering (dogId before color). Is this something that can be done? Or is it simply not supported?

Extra: I know that this can be archieved with other serializers like the well-known JMS with @AccessOrder annotation but I am unable to use that for technical reasons.

Any help is appreciated!

Diplodoco
  • 71
  • 1
  • 7

1 Answers1

0

I think that behaviour depends of the order of your getter and setters.

I'm not sure but the workaround could be to redefine your getters and setters in your child class like so :

class Dog
{
    /**
     * @OA\Property(type="integer")
     * @var int
     */
    protected $dogId;

    public function __construct(int $dogId)
    {
        $this->dogId             = $dogId;
    }

    // ... Getters and setters
}

class DogDetails extends Dog
{
    /**
     * @OA\Property(type="string")
     * @var string
     */
    protected $color;

    public function __construct(int $dogId, string $color)
    {
        parent::__construct($dogId);
        $this->color        = $color;
    }

   // redefine user getter setters
   public function getId(){
     return parent::getDogId();
   }
   public function setId($id){
     parent::setDogId($id);
   }
   // then your actual getter and setters
   public function getColor(){
     return $this->color;
   }
   public function setColor($color){
     $this->color = $color
   }


}

Floxblah
  • 152
  • 9