Search code examples
restsymfonyfosrestbundle

How to expose function result with FosRestBundle?


I am developing an REST API for our system using Symfony2 with FosRestBundle. FosRestBundle is a very good tool but it seems have one limitation: Only properties ( priviate, protected and public ) can be exposed to the API.

I would like to expose a derived property that calculated based on two other fields ( for example full name = firstName+lastName ) and also property thats describe a relationship ( e.g the category name of a product instead of the category ID of a product )

However the @Expose annotation can only work on properties.

I've tried creating a dummy property, set that property in the constructor ( works when creating a new one) and in Doctrine lifecycle postLoad event handler (works when loads from the database ) and it is working. But I don't like this approach as it creates overhead and extra coding even when the Entity class is not used by the API.

I wonder if there's a better way to achieve this.


Solution

  • After looking around for answer, I've found a solution, along with the @Expose annotation, the JMS serializer comes with another annotation for just that purpose: @Accessor

    /**
     * @REST\Accessor(getter="getName")
     * @REST\Expose
     */
    private $name;
    
    
    /**
     * Return a name of the license
     *
     * @return string
     */
    public function getName()
    {
    
        return $this->getProduct()->getName();
    }
    

    Yes, a dummy property is still required, but you can make it private and it is much better than the method I tried before. I hope this can save someone some time.