简体   繁体   中英

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 ( eg 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.

You can use virtual property to return the value that returned by the function as a virtual property you can found more in http://jmsyst.com/libs/serializer/master/reference/annotations#virtualproperty

/**
 *
 * @VirtualProperty()
 * @SerializedName("fullName")
 */
public function getName()
{
    // return name;
}

so when the this object is serialized it will return an object with fullName property which is the value returned by getName function.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM