dev-master
9999999-dev https://github.com/mehlah/li3_jbuilderCreate JSON structures via a DSL
MIT License
The Requires
- php >=5.3
- composer/installers *
by Mehdi Lahmam B.
api json
Create JSON structures via a DSL
To demonstrate the befinits of this libary, weâll use a simple application.
This app has many discussions
and weâd like to add a JSON representation for each discussion
that we can fetch by appending .json
to the discussionâs URL.
If we try this weâll see the JSON representation of the discussion., (*1)
, (*2)
The JSON returned includes all of the discussionâs attributes but what if we want to customize it?
This is where things can start to get ugly. We can call to('json')
on the discussion and customize
whatâs returned.
Letâs say that we want the id, subject and content fields from the discussion along with its author
and the same fields from the discussionâs messages., (*3)
public function show() { $discussion = Discussions::find($this->request->id); if (!$discussion) { return $this->redirect('/discussions'); } if ($this->request->is('json')) { // we don't want to expose this unset($discussion->created_at); // additional data comes from associated Author and Comments records. $discussion->author = [ 'name' => 'Mehdi Lahmam B.', 'id' => '1234' ]; $discussion->comments = [ ['content' => 'w00t', 'author' => 'John Doe'], ['content' => 'This is sexy', 'author' => 'Jimmy'] ]; return compact('discussion'); } return compact('discussion'); }
We can try this by reloading the page again. When we do we see the customized JSON response including the associated Author and Comments records., (*4)
, (*5)
This works, but the code weâve used isnât very pretty., (*6)
Coming soon !, (*7)
Create JSON structures via a DSL
MIT License
api json