How to use JSONAPI in PHP

php中世界最好的语言
Release: 2018-04-13 16:03:09
Original
1823 people have browsed it

This time I will bring you how to use JSONAPI in PHP. What are theprecautionswhen using JSONAPI in PHP? Here are practical cases, let’s take a look.

Now the main job of server programmers is no longer to set templates, but to write JSON-based APIs interface. Unfortunately, everyone often has very different styles of writing interfaces, which brings a lot of unnecessary communication costs to system integration. If you have similar troubles, you might as well pay attention to JSONAPI , it is a specification standard for building APIs based on JSON. A simple API interface looks roughly as follows:

JSONAPI

A brief explanation: data in the root node is used to place the content of the main object, where type and id It is a required field and is used to represent the type and identity of the main object. All other simple attributes are placed in attributes In, if the main object has one-to-one, one-to-many and other related objects, then it is placed in relationships, but only through type and id A link is placed in the field, and the actual content of the associated object is placed inincluded in the root contact.

With JSONAPI, the data parsing process becomes standardized, saving unnecessary communication costs. However, it is still very troublesome to manually construct JSONAPI data. Fortunately, by using Fractal, the implementation process can be relatively automated. If the above example is implemented using Fractal, it will probably look like this:

 1, 'title' => 'JSON API paints my bikeshed!', 'body' => 'The shortest article. Ever.', 'author' => [ 'id' => 42, 'name' => 'John', ], ], ]; $manager = new Manager(); $resource = new Collection($articles, new ArticleTransformer()); $manager->parseIncludes('author'); $manager->createData($resource)->toArray(); ?>
Copy after login

If I had to choose my favorite PHP toolkit, Fractal would definitely be on the list. It hides the implementation details so that users don’t need to know JSONAPI at all. The agreement is ready to start. But if you want to use it in your own project, instead of using Fractal directly, you can try Fractalistic, which is better for Fractal Encapsulated to make it easier to use:

collection($articles) ->transformWith(new ArticleTransformer()) ->includeAuthor() ->toArray(); ?>
Copy after login

If you are writing PHP naked, then Fractalistic is basically the best choice, but if you use some full-stack framework, then Fractalistic may not be elegant enough because it cannot be more perfectly integrated with the existing functions of the framework itself. Taking Lavaral as an example, it has a built-in API Resources function, based on this I implemented a JsonApiSerializer, which can be perfectly integrated with the framework. The code is as follows:

resource = $resource; $this->resourceValue = $resourceValue; } public function jsonSerialize() { foreach ($this->resourceValue as $key => $value) { if ($value instanceof Resource) { $this->serializeResource($key, $value); } else { $this->serializeNonResource($key, $value); } } if (!$this->isRootResource()) { return $this->data; } $result = [ 'data' => $this->data, ]; if (static::$included) { $result['included'] = static::$included; } if (!$this->resource->resource instanceof AbstractPaginator) { return $result; } $paginated = $this->resource->resource->toArray(); $result['links'] = $this->links($paginated); $result['meta'] = $this->meta($paginated); return $result; } protected function serializeResource($key, $value, $type = null) { if ($type === null) { $type = $key; } if ($value->resource instanceof MissingValue) { return; } if ($value instanceof ResourceCollection) { foreach ($value as $k => $v) { $this->serializeResource($k, $v, $type); } } elseif (is_string($type)) { $included = $value->resolve(); $data = [ 'type' => $included['type'], 'id' => $included['id'], ]; if (is_int($key)) { $this->data['relationships'][$type]['data'][] = $data; } else { $this->data['relationships'][$type]['data'] = $data; } static::$included[] = $included; } else { $this->data[] = $value->resolve(); } } protected function serializeNonResource($key, $value) { switch ($key) { case 'id': $value = (string)$value; case 'type': case 'links': $this->data[$key] = $value; break; default: $this->data['attributes'][$key] = $value; } } protected function links($paginated) { return [ 'first' => $paginated['first_page_url'] ?? null, 'last' => $paginated['last_page_url'] ?? null, 'prev' => $paginated['prev_page_url'] ?? null, 'next' => $paginated['next_page_url'] ?? null, ]; } protected function meta($paginated) { return [ 'current_page' => $paginated['current_page'] ?? null, 'from' => $paginated['from'] ?? null, 'last_page' => $paginated['last_page'] ?? null, 'per_page' => $paginated['per_page'] ?? null, 'to' => $paginated['to'] ?? null, 'total' => $paginated['total'] ?? null, ]; } protected function isRootResource() { return isset($this->resource->isRoot) && $this->resource->isRoot; } } ?>
Copy after login

The corresponding Resource is basically the same as before, except that the return value has been changed:

 'articles', 'id' => $this->id, 'name' => $this->name, 'author' => $this->whenLoaded('author'), ]; return new JsonApiSerializer($this, $value); } } ?>
Copy after login

The corresponding Controller is almost the same as the original, except that an isRoot attribute is added to identify the root:

article = $article; } public function show($id) { $article = $this->article->with('author')->findOrFail($id); $resource = new ArticleResource($article); $resource->isRoot = true; return $resource; } } ?>
Copy after login

The whole process does not intrude too much on Laravel's architecture. It can be said that Laravel currently implements JSONAPI The best solution. If you are interested, you can study JsonApiSerializer. Although there are only more than a hundred lines of code to implement, I spent a lot of effort to achieve it. It can be said that every step of the way is hard work.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to speed up and optimize vue-cli code

Vue.js universal application framework Nuxt.js Use detailed explanation

#JS to implement label scrolling switching

The above is the detailed content of How to use JSONAPI in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!