项目作者: motia

项目描述 :
laravel entities serializer
高级语言: PHP
项目地址: git://github.com/motia/laravel-jms-serializer.git
创建时间: 2018-12-06T14:35:30Z
项目社区:https://github.com/motia/laravel-jms-serializer

开源协议:MIT License

下载


laravel-jms-serializer

A Library for serializer intergration with Laravel.
Useful to serialize doctrine entities or any plain objects in general.

This package injects into your application two service contracts:

  • DataNormalizer: converts the data to a php array.
  • ResponseSerializer: normalizes the data using DataNormalizer then builds a Illuminate\Http\Response object containting it.

The default implemntation of ResponseSerializer follows the jsend api schema

Installation

  1. composer require motia/laravel-jms-serializer

Register the package service provider by adding it toconfig/app.php

  1. ...
  2. Motia\LaravelJMSSerializer\SerializerServiceProvider::class
  3. ...

Usage:

  • Inside Controllers

    1. // MyController.php
    2. ...
    3. public function hello(\Motia\LaravelJMSSerializer\Contracts\ResponseSerializer $serializer) {
    4. ...
    5. return $serializer->success($object);
    6. }
  • The serializer can also indicate errors and failed requests.

    1. // return a successful response with status 200
    2. $serializer->success($data = null, $code= 200, $context = null);
    3. // return a failure response, for example validation
    4. $serializer->fail($data = null, $code = 422, $context = null);
    5. // return an error response, for unexpceted errors
    6. $serializer->error($message, $data = null, $code = 500, $context = null);
    7. // return the normalized array of the php objects; equivalent to `DataNormalizer::normalize()`
    8. $serializer->normalize($object, $context = null);

Data type serializers

The package supports serializing:

  • the Laravel pagination object LengthAwarePaginator
    ['pagination' => ['total' => 5, 'perPage' => 10... ], 'items' => [...] ] The property‘items’ can be renamed using the serializer context 'itemsKey' property like that:
    1. $context = SerializationContext::create()->setAttribute('itemsKey', 'subscribers');

The 'items' property of the array can be renamed using

  • Ramsey\Uuid\Uuid
  • Carbon\Carbon: serialized to a ISO8086 string readable by all browsers.