Now the main job of server programmers is no longer to set templates, but to write JSON-based API interfaces. 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, which is a standard for building APIs based on JSON, a simple The API interface of To represent the type and identity of the main object, other simple attributes are placed in attributes. If the main object has one-to-one, one-to-many and other related objects, then they are placed in relationships, but only a link is placed through the type and id fields. , the actual contents of the associated objects are all placed in included 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:
##<?php use League\Fractal\Manager; use League\Fractal\Resource\Collection; $articles = [ [ 'id' => 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(); ?>
If I were asked to choose my favorite PHP toolkit, Fractal would definitely be on the list. It hides the implementation details and allows users to get started without having to understand the JSONAPI protocol at all. But if you want to use it in your own project, instead of using Fractal directly, you can try Fractalistic, which encapsulates Fractal to make it easier to use:
<?php Fractal::create() ->collection($articles) ->transformWith(new ArticleTransformer()) ->includeAuthor() ->toArray(); ?>
If you are writing PHP naked, then Fractalistic is basically the best choice. However, if you use some full-stack frameworks, then Fractalistic may not be elegant enough because it cannot be more perfect with the existing functions of the framework itself. Integration, taking Lavaral as an example, it has a built-in API Resources function. On this basis, I implemented a JsonApiSerializer, which can be perfectly integrated with the framework. The code is as follows:
<?php namespace App\Http\Serializers; use Illuminate\Http\Resources\MissingValue; use Illuminate\Http\Resources\Json\Resource; use Illuminate\Http\Resources\Json\ResourceCollection; use Illuminate\Pagination\AbstractPaginator; class JsonApiSerializer implements \JsonSerializable { protected $resource; protected $resourceValue; protected $data = []; protected static $included = []; public function __construct($resource, $resourceValue) { $this->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; } } ?>
The corresponding Resource is basically the same as before, except that the return value has been changed:
<?php namespace App\Http\Resources; use App\Article; use Illuminate\Http\Resources\Json\Resource; use App\Http\Serializers\JsonApiSerializer; class ArticleResource extends Resource { public function toArray($request) { $value = [ 'type' => 'articles', 'id' => $this->id, 'name' => $this->name, 'author' => $this->whenLoaded('author'), ]; return new JsonApiSerializer($this, $value); } } ?>
The corresponding Controller is also similar to the original, except that an isRoot attribute is added, using To identify the root:
<?php namespace App\Http\Controllers; use App\Article; use App\Http\Resources\ArticleResource; class ArticleController extends Controller { protected $article; public function __construct(Article $article) { $this->article = $article; } public function show($id) { $article = $this->article->with('author')->findOrFail($id); $resource = new ArticleResource($article); $resource->isRoot = true; return $resource; } } ?>
The whole process does not intrude too much into Laravel's architecture. It can be said to be the best solution for Laravel to implement JSONAPI at present. Those who are interested You can study the implementation of JsonApiSerializer. Although there are only more than a hundred lines of code, I spent a lot of effort to implement it. It can be said that every step is hard work.
Related recommendations:
Example detailed explanation javascript to download json format array For excel tables
Several cases of JSON value transmission and PHP reception
The above is the detailed content of Application of JSONAPI in PHP. For more information, please follow other related articles on the PHP Chinese website!