Home  >  Article  >  Web Front-end  >  Application of JSONAPI in PHP

Application of JSONAPI in PHP

小云云
小云云Original
2017-12-25 14:54:561439browse

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 = [
  [
    &#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();
?>

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 = [
      &#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;
  }
}
?>

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);
  }
}
?>

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(&#39;author&#39;)->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:


Summary of how to use Ajax and jsonp


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!

Statement:
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