Home > Web Front-end > JS Tutorial > body text

How to use JSONAPI in PHP

亚连
Release: 2018-06-15 17:27:36
Original
1229 people have browsed it

This article mainly introduces an in-depth analysis of the application of JSONAPI in PHP. Friends who need it can refer to it

Now the main job of server programmers is no longer to set templates, but to write based on JSON API 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, 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 = [
  [
    &#39;id&#39; => 1,
    &#39;title&#39; => &#39;JSON API paints my bikeshed!&#39;,
    &#39;body&#39; => &#39;The shortest article. Ever.&#39;,
    &#39;author&#39; => [
      &#39;id&#39; => 42,
      &#39;name&#39; => &#39;John&#39;,
    ],
  ],
];
$manager = new Manager();
$resource = new Collection($articles, new ArticleTransformer());
$manager->parseIncludes(&#39;author&#39;);
$manager->createData($resource)->toArray();
?>
Copy after login

If you ask me to choose my favorite Among the PHP toolkits, Fractal must be on the list. It hides the implementation details and allows users to get started without knowing 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();
?>
Copy after login

If you are writing PHP naked If so, then Fractalistic is basically the best choice. However, 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 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 = [
      &#39;data&#39; => $this->data,
    ];
    if (static::$included) {
      $result[&#39;included&#39;] = static::$included;
    }
    if (!$this->resource->resource instanceof AbstractPaginator) {
      return $result;
    }
    $paginated = $this->resource->resource->toArray();
    $result[&#39;links&#39;] = $this->links($paginated);
    $result[&#39;meta&#39;] = $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 = [
        &#39;type&#39; => $included[&#39;type&#39;],
        &#39;id&#39; => $included[&#39;id&#39;],
      ];
      if (is_int($key)) {
        $this->data[&#39;relationships&#39;][$type][&#39;data&#39;][] = $data;
      } else {
        $this->data[&#39;relationships&#39;][$type][&#39;data&#39;] = $data;
      }
      static::$included[] = $included;
    } else {
      $this->data[] = $value->resolve();
    }
  }
  protected function serializeNonResource($key, $value)
  {
    switch ($key) {
      case &#39;id&#39;:
        $value = (string)$value;
      case &#39;type&#39;:
      case &#39;links&#39;:
        $this->data[$key] = $value;
        break;
      default:
        $this->data[&#39;attributes&#39;][$key] = $value;
    }
  }
  protected function links($paginated)
  {
    return [
      &#39;first&#39; => $paginated[&#39;first_page_url&#39;] ?? null,
      &#39;last&#39; => $paginated[&#39;last_page_url&#39;] ?? null,
      &#39;prev&#39; => $paginated[&#39;prev_page_url&#39;] ?? null,
      &#39;next&#39; => $paginated[&#39;next_page_url&#39;] ?? null,
    ];
  }
  protected function meta($paginated)
  {
    return [
      &#39;current_page&#39; => $paginated[&#39;current_page&#39;] ?? null,
      &#39;from&#39; => $paginated[&#39;from&#39;] ?? null,
      &#39;last_page&#39; => $paginated[&#39;last_page&#39;] ?? null,
      &#39;per_page&#39; => $paginated[&#39;per_page&#39;] ?? null,
      &#39;to&#39; => $paginated[&#39;to&#39;] ?? null,
      &#39;total&#39; => $paginated[&#39;total&#39;] ?? 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:

<?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 = [
      &#39;type&#39; => &#39;articles&#39;,
      &#39;id&#39; => $this->id,
      &#39;name&#39; => $this->name,
      &#39;author&#39; => $this->whenLoaded(&#39;author&#39;),
    ];
    return new JsonApiSerializer($this, $value);
  }
}
?>
Copy after login

The corresponding Controller is similar to the original, except that an isRoot attribute is added 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(&#39;author&#39;)->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 At present, Laravel implements the optimal solution for JSONAPI. If you 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 of the way is hard work.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Set the background image in Vue

How to use vue less to implement a simple skin change function

How to implement the same interview question component using angular, react and vue

Use jQuery to automatically load when scrolling to the bottom

How to implement modal dialog box in Angular2.0

How to implement motion buffering effect in JS (detailed tutorial)

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
Popular Tutorials
More>
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!