motia/laravel-jms-serializer

0.1.2 2019-12-04 12:56 UTC

This package is auto-updated.

Last update: 2024-09-05 00:08:50 UTC


README

一个用于与Laravel集成的serializer库。适用于序列化Doctrine实体或任何普通对象。

此包向您的应用程序注入两个服务契约

  • DataNormalizer:将数据转换为PHP数组。
  • ResponseSerializer:使用DataNormalizer规范化数据,然后构建包含数据的Illuminate\Http\Response对象。

ResponseSerializer的默认实现遵循jsend API模式

安装

composer require motia/laravel-jms-serializer

通过将其添加到config/app.php来注册包服务提供者

  ...
    Motia\LaravelJMSSerializer\SerializerServiceProvider::class 
  ...

用法

  • 在控制器内部
  // MyController.php
  ...
   public function hello(\Motia\LaravelJMSSerializer\Contracts\ResponseSerializer $serializer) {
     ...
    return $serializer->success($object);
  }
  • 序列化器还可以指示错误和失败的请求。
    // return a successful response with status 200
    $serializer->success($data = null, $code= 200, $context = null);
    // return a failure response, for example validation
    $serializer->fail($data = null, $code = 422, $context = null);
    // return an error response, for unexpceted errors 
    $serializer->error($message, $data = null, $code = 500, $context = null);
    // return the normalized array of the php objects; equivalent to `DataNormalizer::normalize()`
    $serializer->normalize($object, $context = null);

数据类型序列化器

此包支持序列化

  • Laravel分页对象LengthAwarePaginator ['pagination' => ['total' => 5, 'perPage' => 10... ], 'items' => [...] ] 属性 'items' 可以使用序列化器上下文属性 'itemsKey' 重命名,如下所示
$context = SerializationContext::create()->setAttribute('itemsKey', 'subscribers');

使用以下方法重命名数组的'items'属性

  • Ramsey\Uuid\Uuid
  • Carbon\Carbon:序列化为ISO8086字符串,所有浏览器都可读取。