Apigility:如何渲染嵌入对象?

时间:2015-10-03 05:44:13

标签: rest apigility

如何在Apigility中渲染嵌入对象?例如,如果我有一个'用户'对象并且它组成一个'country'对象,我应该将'country'对象渲染为嵌入对象吗?我应该怎么做?

我正在使用Zend\Stdlib\Hydrator\ArraySerializable。我的getArrayCopy()方法只返回我想要公开的属性数组。数组键是属性名称。数组值是属性值。在user->country的情况下,值是对象,而不是标量。

当我从UserResource->fetch()返回用户对象时,以下是它的呈现方式:

{
  "id": "1",
  "firstName": "Joe",
  "lastName": "Bloggs",
  "status": "Active",
  "email": "test@example.com",
  "country": {
    "code": "AU",
    "name": "Australia"
  },
  "settings": "0",
  "_links": {
    "self": {
      "href": "http://api.mydomain.local/users/1"
    }
  }
}

请注意,“国家/地区”不在_embedded字段中。如果它应该在_embedded中,我会认为Apigility会自动执行此操作(因为它会自动添加_links对象)。

作为相关问题,如何返回其他相关链接,例如后退,前进等?

2 个答案:

答案 0 :(得分:1)

获取Apigility以呈现嵌入资源的最简单方法是在存在与嵌入对象关联的API /资源时。我的意思是你有一个具有国家实体的API资源。在这种情况下,如果您的getArrayCopy返回CountryEntity,Apigility会自动将其呈现为嵌入式资源。

如果您的getArrayCopy将国家/地区作为包含代码和名称的数组返回,那么您最终会看到所看到的内容。

对于另一部分,当您返回Paginator时,first,last,prev和next的rel链接将来自fetchAll方法。您的集合已经从此扩展,但它需要一个适配器。代码看起来像这样:

public function fetchAll($params)
{
    // Return a \Zend\Db\Select object that will retrieve the 
    // stuff you want from the database
    $select = $this->service->fetchAll($params);

    $entityClass = $this->getEntityClass();
    $entity      = new $entityClass();

    $hydrator  = new \Zend\Stdlib\ArraySerializable();
    $prototype = new \Zend\Db\ResultSet\HydratingResultSet($hydrator, $entity);
    $paginator = new \Zend\Paginator\Adapter\DbSelect($select, $this->sql, $prototype);

    $collectionClass = $this->getCollectionClass();
    return new $collectionClass($paginator);
}

还有其他的paginator适配器 - 一个ArrayAdapter,它将接收一个大的数组,然后对它进行分页,这样你只能得到所需的结果数。如果你将它与数据库结果一起使用,那么你可能会检索并丢弃大量结果。 DbSelect paginator将修改$ select对象以自动添加limit和order子句,因此您只需检索所需的位。如果你正在使用DbTableGateway,Iterators甚至回调,也有适配器。当然,您也可以实现自己的目标。

希望这会有所帮助。如果您有更具体的需求或澄清,请发表评论,我会尽力而为。

答案 1 :(得分:1)

我在github上发布了这个例子。

https://github.com/martins-smb/apigility-renderCollection-example

希望这有帮助。

相关问题