如何使用 FosRestBundle 公开函数结果? [英] How to expose function result with FosRestBundle?

查看:46
本文介绍了如何使用 FosRestBundle 公开函数结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Symfony2 和 FosRestBundle 为我们的系统开发 REST API.FosRestBundle 是一个非常好的工具,但它似乎有一个限制:只有属性(private、protected 和 public)可以暴露给 API.

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.

我想公开一个基于其他两个字段计算的派生属性(例如 full name = firstName+lastName )以及描述关系的属性(例如产品的类别名称而不是产品的类别 ID产品)

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 )

然而@Expose 注解只能作用于属性.

However the @Expose annotation can only work on properties.

我尝试创建一个虚拟属性,在构造函数中设置该属性(在创建新属性时有效)和 Doctrine 生命周期 postLoad 事件处理程序(在从数据库加载时有效)并且它正在工作.但我不喜欢这种方法,因为即使 API 不使用实体类,它也会产生开销和额外的编码.

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.

推荐答案

在四处寻找答案后,我找到了一个解决方案,连同 @Expose 注释,JMS 序列化程序附带了另一个用于此目的的注释:@存取器

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.

这篇关于如何使用 FosRestBundle 公开函数结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆