mehlah / li3_jbuilder
Create JSON structures via a DSL
Installs: 8
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 4
Forks: 0
Open Issues: 0
Type:lithium-library
Requires
- php: >=5.3
- composer/installers: *
This package is not auto-updated.
Last update: 2025-04-12 16:41:38 UTC
README
Adding JSON Responses to an Application 
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.
Customizing The Response
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.
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.
This works, but the code we’ve used isn’t very pretty.
A better way
Coming soon !