nilportugues/laravel5-jsend

Laravel 5 JSend API 转换器包

1.3.0 2016-01-05 13:43 UTC

This package is not auto-updated.

Last update: 2024-09-20 22:12:47 UTC


README

Scrutinizer Code Quality SensioLabsInsight Latest Stable Version Total Downloads License Donate

兼容Laravel 5.0、5.1和5.2

安装

使用Composer安装包

$ composer require nilportugues/laravel5-jsend

Laravel 5/Lumen 配置

步骤 1:添加服务提供者

Laravel

打开 config/app.php,在 providers 数组下添加以下行

'providers' => [

    //...
    \NilPortugues\Laravel5\JSend\Laravel5JSendServiceProvider::class,
],

Lumen

打开 bootstrap/app.php,在 return $app; 语句之前添加以下行

$app->register(\NilPortugues\Laravel5\JSend\Laravel5JSendServiceProvider::class);
$app->configure('jsend');

同时,通过取消注释来启用 Facades

$app->withFacades();

步骤 2:添加映射

config/ 目录下创建一个 jsend.php 文件。该文件应返回一个包含所有类映射的数组。

步骤 3:使用方法

例如,假设以下对象已从仓库中检索到,假设为 PostRepository - 这是由 Eloquent 或其他您喜欢的风味实现的

use Acme\Domain\Dummy\Post;
use Acme\Domain\Dummy\ValueObject\PostId;
use Acme\Domain\Dummy\User;
use Acme\Domain\Dummy\ValueObject\UserId;
use Acme\Domain\Dummy\Comment;
use Acme\Domain\Dummy\ValueObject\CommentId;

//$postId = 9;
//PostRepository::findById($postId); 

$post = new Post(
  new PostId(9),
  'Hello World',
  'Your first post',
  new User(
      new UserId(1),
      'Post Author'
  ),
  [
      new Comment(
          new CommentId(1000),
          'Have no fear, sers, your king is safe.',
          new User(new UserId(2), 'Barristan Selmy'),
          [
              'created_at' => (new \DateTime('2015/07/18 12:13:00'))->format('c'),
              'accepted_at' => (new \DateTime('2015/07/19 00:00:00'))->format('c'),
          ]
      ),
  ]
);

以及一系列放置在 config/jsend.php 中的映射,这些映射需要使用 命名路由,这样我们就可以使用 route() 辅助函数

<?php
//config/jsend.php
return [
    [
        'class' => 'Acme\Domain\Dummy\Post',
        'alias' => 'Message',
        'aliased_properties' => [
            'author' => 'author',
            'title' => 'headline',
            'content' => 'body',
        ],
        'hide_properties' => [

        ],
        'id_properties' => [
            'postId',
        ],
        'urls' => [
            'self' => ['name' => 'get_post'], //named route
            'comments' => ['name' => 'get_post_comments'], //named route
        ],
    ],
    [
        'class' => 'Acme\Domain\Dummy\ValueObject\PostId',
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'postId',
        ],
        'urls' => [
            'self' => ['name' => 'get_post'], //named route
        ],
    ],
    [
        'class' => 'Acme\Domain\Dummy\User',
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'userId',
        ],
        'urls' => [
            'self' => ['name' => 'get_user'], //named route
            'friends' => ['name' => 'get_user_friends'], //named route
            'comments' => ['name' => 'get_user_comments'], //named route
        ],
    ],
    [
        'class' => 'Acme\Domain\Dummy\ValueObject\UserId',
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'userId',
        ],
        'urls' => [
            'self' => ['name' => 'get_user'], //named route
            'friends' => ['name' => 'get_user_friends'], //named route
            'comments' => ['name' => 'get_user_comments'], //named route
        ],
    ],
    [
        'class' => 'Acme\Domain\Dummy\Comment',
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'commentId',
        ],
        'urls' => [
            'self' => ['name' => 'get_comment'], //named route
        ],
    ],
    [
        'class' => 'Acme\Domain\Dummy\ValueObject\CommentId',
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'commentId',
        ],
        'urls' => [
            'self' => ['name' => get_comment'], //named route
        ],
    ],
];

命名路由属于 app/Http/routes.php。以下是提供的路由映射的示例

Laravel

Route::get(
  '/post/{postId}',
  ['as' => 'get_post', 'uses' => 'PostController@getPostAction']
);

Route::get(
  '/post/{postId}/comments',
  ['as' => 'get_post_comments', 'uses' => 'CommentsController@getPostCommentsAction']
);

//...

Lumen

$app->get(
  '/post/{postId}',
  ['as' => 'get_post', 'uses' => 'PostController@getPostAction']
);

$app->get(
  '/post/{postId}/comments',
  ['as' => 'get_post_comments', 'uses' => 'CommentsController@getPostCommentsAction']
);

//...

所有这些设置都允许您轻松使用 JSendSerializer 服务如下

<?php

namespace App\Http\Controllers;

use Acme\Domain\Dummy\PostRepository;
use NilPortugues\Laravel5\JSend\JSendSerializer;
use NilPortugues\Laravel5\JSend\JSendResponseTrait;


class PostController extends \Laravel\Lumen\Routing\Controller
{
    use JSendResponseTrait;

    /**
     * @var PostRepository
     */
    private $postRepository;

    /**
     * @var JSendSerializer
     */
    private $serializer;

    /**
     * @param PostRepository $postRepository
     * @param JSendSerializer $jSendSerializer
     */
    public function __construct(PostRepository $postRepository, JSendSerializer $jSendSerializer)
    {
        $this->postRepository = $postRepository;
        $this->serializer = $jSendSerializer;
    }

    /**
     * @param int $postId
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function getPostAction($postId)
    {
        $post = $this->postRepository->findById($postId);

        /** @var \NilPortugues\Api\JSend\JSendTransformer $transformer */
        $transformer = $this->serializer->getTransformer();
        $transformer->setSelfUrl(route('get_post', ['postId' => $postId]));
        $transformer->setNextUrl(route('get_post', ['postId' => $postId+1]));

        return $this->response($this->serializer->serialize($post));
    }
}

输出

HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/json; charset=utf-8
{
    "status": "success",
    "data": {
        "post_id": 9,
        "title": "Hello World",
        "content": "Your first post",
        "author": {
            "user_id": 1,
            "name": "Post Author"
        },
        "comments": [
            {
                "comment_id": 1000,
                "dates": {
                    "created_at": "2015-07-18T12:13:00+00:00",
                    "accepted_at": "2015-07-19T00:00:00+00:00"
                },
                "comment": "Have no fear, sers, your king is safe.",
                "user": {
                    "user_id": 2,
                    "name": "Barristan Selmy"
                }
            }
        ]
    },
    "links": {
        "self": {
            "href": "http://example.com/post/9"
        },
        "next": {
            "href": "http://example.com/post/10"
        }
    }
}

响应对象(JSendResponseTrait)

以下 JSendResponseTrait 方法提供了返回正确头和 HTTP 状态码的方法

    private function errorResponse($message, $code = 500, $data = null);
    private function failResponse($json);
    private function response($json);

## 质量

要运行 PHPUnit 测试,请进入测试目录并输入 phpunit。

此库试图遵守 PSR-1PSR-2PSR-4PSR-7

如果您发现任何遵守上的疏忽,请通过 Pull Request 发送补丁。


## 贡献

欢迎对包的贡献!


## 支持

您可以通过以下方式之一与我联系


## 作者

许可

代码库采用MIT 许可证