2016-02-01 35 views
1

我爲建設有API的平臺我的第一個休息API爲AngularJs應用,水合物加入實體API的平臺

我想我所有的項目實體,像探微這裏(用我的網址/項目):

{ 
    "@context": "/contexts/Project", 
    "@id": "/projects", 
    "@type": "hydra:PagedCollection", 
    "hydra:totalItems": 19, 
    "hydra:itemsPerPage": 30, 
    "hydra:firstPage": "/projects", 
    "hydra:lastPage": "/projects", 
    "hydra:member": [ 
    { 
     "@id": "/projects/1", 
     "@type": "Project", 
     "name": "test1", 
     "parent": null, 
     "createdAt": "2014-12-22T11:38:13+01:00", 
     "updatedAt": null, 
     "deletedAt": null 
    }, 
    { 
     "@id": "/projects/2", 
     "@type": "Project", 
     "name": "test2", 
     "parent": null, 
     "createdAt": "2014-12-22T17:02:50+01:00", 
     "updatedAt": null, 
     "deletedAt": null 
    }, 
    { 
     "@id": "/projects/3", 
     "@type": "Project", 
     "name": "test3", 
     "parent": "/projects/2", 
     "createdAt": "2014-12-22T18:28:50+01:00", 
     "updatedAt": null, 
     "deletedAt": null 
    } 
    ] 
} 

但你可以看到我的項目可以有父母,所以我得到了我父項目的基準(如本/項目/ 2)

我可以以JSON直接獲取項目對象,而不是引用喜歡這個 ?

{ 
     "@id": "/projects/3", 
     "@type": "Project", 
     "name": "test3", 
     "parent": { 
      "@id": "/projects/2", 
      "@type": "Project", 
      "name": "test2", 
      "parent": null, 
      "createdAt": "2014-12-22T17:02:50+01:00", 
      "updatedAt": null, 
      "deletedAt": null 
     }, 
     "createdAt": "2014-12-22T18:28:50+01:00", 
     "updatedAt": null, 
     "deletedAt": null 
    } 

這是Rest APi的一個很好的實踐?

回答

0

API平臺具有用於embedding relations in the parent JSON document的內置函數。

你的實體將是這樣的:

namespace AppBundle\Entity; 

use Symfony\Component\Serializer\Annotation\Groups; 

class Project 
{ 
    private $id; 

    /** @Groups({"embed"}) */ 
    private $parent; 

    /** @Groups({"embed"}) */ 
    private $name; 

    /** @Groups({"embed"}) */ 
    private $createdAt; 

    // ... 
} 

以及服務定義:

# app/config/services.yml 
services: 
    # ... 

    resource.offer: 
     parent: api.resource 
     arguments: [ 'AppBundle\Entity\Offer' ] 
     calls: 
      -  method: initNormalizationContext 
        arguments: [ { groups: [ embed ] } ] 
     tags:  [ { name: api.resource } ] 

要小心,它會嵌入父以及父的父等等。如果你想改變這個,你需要創建一個自定義標準化程序。由於the new @MaxDepth annotation,Symfony 3.1的發佈將會更直接。

+0

我嘗試這個,但是當我調用它時它不會改變任何東西,它仍然是一些url格式,而不是嵌入格式。我需要改變一些配置嗎? –

+0

好了之後做了我的項目作曲家更新它的作品謝謝! –

+0

app/console c:c –