K
K
Kirill Nesmeyanov2014-04-30 23:46:36
PHP
Kirill Nesmeyanov, 2014-04-30 23:46:36

Is there a Rabl analogue for PHP (filtering serialized data)?

The situation is the following. Let's say there is a /blog/:id route that leads to a controller method:

public function show($id)
{
    return Blog::find($id);
}

The controller method calls the find method on the Blog model and, if successful, returns the object of this blog post, then the data is automatically serialized into json of the form:
{
  "id": 1,
  "title": "Тестовая запись",
  "content": "****** *****",
  "original_content": "***"
 и т.д.
}


So, the question is as follows - a mechanism is required that would allow cutting off unnecessary data and adding the required ones, for example:
public function show($id)
{
    return (new JsonData(Blog::find($id)))
      ->with(['id', 'title', 'content', 'user.login', 'user.avatar', 'user.id']);
}

What would be similar (I give an example without taking into account the fact that find can return null):
public function show($id)
{
    $blog = Blog::find($id);
    return [
      'id' => $blog->id,
      'title' => $blog->title,
      'content' => $blog->content,
      'user' => [
          'id' => $blog->user->id,
          'avatar' => $blog->user->avatar,
          'login' => $blog->user->login
      ]
    ];
}


There is a great gem for rubies, called Rabl, which allows you to do exactly what you need:
attributes :id, :title, :description, :start, :end, :location
child :creator => :creator do
  extends 'users/base'
end
 
## JSON output:
# {
#     "event": {
#         "id": 7,
#         "title": "Et earum sed fuga.",
#         "description": "Quis sed ..e ad.",
#         "start": "2011-05-31T08:31:45Z",
#         "end": "2011-06-01T08:31:45Z",
#         "location": "Saul Tunnel",
#         "creator": {
#             "id": 1,
#             "username": "alanna",
#             "email": "rubie@hayes.name",
#             "display_name": "Mrs. Gaylord Hoeger"
#         }
#     }
# }

Maybe someone has experienced something similar? Any advice?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-05-01
Protko @Fesor

JMSerializer ? Of course, his documentation is dumb, but he can do everything you want.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question