Advertisement
Guest User

Symfony API Relationship Inclusion Example

a guest
Mar 24th, 2016
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.72 KB | None | 0 0
  1. /**
  2.  * Client Entity
  3.  */
  4. class Client
  5. {
  6.     /**
  7.      * @Groups({"client"})
  8.      *
  9.      * @var integer
  10.      */
  11.     private $id;
  12.  
  13.     /**
  14.      * @Groups({"client"})
  15.      *
  16.      * @var string
  17.      */
  18.     private $name;
  19.  
  20.     /**
  21.      * @Groups({"client"})
  22.      *
  23.      * @var \DateTime
  24.      */
  25.     private $created;
  26.  
  27.     /**
  28.      * @Groups({"project"})
  29.      *
  30.      * @var \Doctrine\Common\Collections\Collection
  31.      */
  32.     private $projects;
  33.    
  34.     // Getters/setters...
  35. }
  36.  
  37. // ------------------------------------------------------------------------------------------------------------
  38.  
  39. /*
  40.  * Base Controller
  41.  */
  42. protected function buildResponse($data, $code = Codes::HTTP_OK)
  43. {
  44.     // ...
  45.    
  46.     $parameters = $this->request->query->all();
  47.     $view = View::create($responseData, $code);
  48.  
  49.     if (array_key_exists('include', $parameters)) {
  50.         $context = SerializationContext::create()->setGroups($parameters['include']);
  51.         $view->setSerializationContext($context);
  52.     }
  53.  
  54.     return $this->viewHandler->handle($view);
  55. }
  56.  
  57. // ------------------------------------------------------------------------------------------------------------
  58.  
  59. /*
  60.  * Query (including a relationship)
  61.  */
  62.  
  63. /posts?include[]=comment
  64.  
  65. {
  66.   id: 3,
  67.   name: "Post 1 title",
  68.   created: "2016-03-22T17:58:16+0000",
  69.   comments: [
  70.     {
  71.       id: 4,
  72.       body: "Comment body..."
  73.     },
  74.     {
  75.       id: 5,
  76.       body: "Comment body..."
  77.     }
  78.   ]
  79. }
  80.  
  81. // ------------------------------------------------------------------------------------------------------------
  82.  
  83. /*
  84.  * Query (no relationships)
  85.  */
  86.  
  87. /clients?include[]=client
  88.  
  89. {
  90.   id: 3,
  91.   name: "Post 1 title",
  92.   created: "2016-03-22T17:58:16+0000"
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement