2017 © Pedro PelĂĄez
 

lithium-library li3_jbuilder

Create JSON structures via a DSL

image

mehlah/li3_jbuilder

Create JSON structures via a DSL

  • Friday, April 12, 2013
  • by mehlah
  • Repository
  • 3 Watchers
  • 1 Stars
  • 2 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

Adding JSON Responses to an Application Build Status

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)

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., (*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)

A better way

Coming soon !, (*7)

Credits

Loosely based on the original, and a PHP port, (*8)

The Versions

12/04 2013

dev-master

9999999-dev https://github.com/mehlah/li3_jbuilder

Create JSON structures via a DSL

  Sources   Download

MIT License

The Requires

 

by Mehdi Lahmam B.

api json