在Laravel API上标准化数据服务器端,例如paularmstrong / normalizr

问题描述 投票:0回答:1

我正在尝试在Laravel API上模仿paularmstrong/normalizr的功能。

下面的代码只是我的想法,未经测试,可能充满错误。

我想知道是否有人知道更好的方法,或者是否有人已经编写了一个方便的软件包?

控制器功能

public function list(Request $request) {
  $items = Item::where(['id' => $id])
        ->with(['sets', 'things'])
        ->take(2);

  $data = [
    'entities' => [
        'items' => $this->toNormalizedResponse($items, ItemResource),
        'sets' => $this->toNormalizedResponse($items, SetResource),
        'things' => $this->toNormalizedResponse($items, ThingResource),
      ],
    'result' => $items->pluck('id')
    ];
  return response()->json($data, $this->getStatusCode(), $headers);   
}    

特质归一化数据

<?php

use Illuminate\Http\JsonResponse;

trait NormalizeResponse
{
    /**
     * Normalize the data
     * @param $collection
     * @param string $jsonResponse Custom JsonResponse
     * @param string $id
     * @return array
     */
    function toNormalizedResponse($collection, $jsonResponse = JsonResponse::class, $id = 'id')
    {
        $collection = $this->getCollection($collection);
        if (is_null($collection)) {
            return [];
        }
        $data = [];

        foreach($collection as $model) {
            $data[$model->$id] = new $jsonResponse($model);
        }

        return $data;
    }

    /**
     * Convert to collection or return null if not an eloquent model
     * @param $collection
     * @return \Illuminate\Support\Collection|null
     */
    private function getCollection($collection) {
        if ($collection instanceof Illuminate\Database\Eloquent\Collection) {
            return $collection;
        }
        if ($collection instanceOf \Illuminate\Database\Eloquent\Model) {
            return collect([$collection]);
        }
        return null;
    }
}

ItemResource code

<?php

namespace App\Resources;

class ItemResource extends JsonResource
{
    public function toArray($request)
    {
        $data = [
            'id'     => (int) $this->id,
            'name'   => $this->name,
            'sets' => (isset ($this->sets)) ? $this->sets->pluck('id') : [],
            'things' => (isset ($this->things)) ? $this->things->pluck('id') : [],
        ];
        return $data;
    }
}

所需的Json结构

{
  entities: {
    sets: {
      23: {
        id: 23,
        name: 'Set 23'
      },
      42: {
        id: 42,
        name: 'Set 42'
      }
    },
    things: {
      21: {
        id: 21,
        name: 'Thing 21'
      },
      33: {
        id: 33,
        name: 'Thing 33'
      }
    },
    items: {
      1: {
        id: 1,
        name: 'Item 1',
        sets: [23],
        things: [33]
      },
      2: {
        id: 2,
        name: 'Item 2',
        sets: [23,42],
        things: [21]
      }
    }
  },
  result: [1, 2]
}
php laravel normalization
1个回答
0
投票

我一直在寻找类似的解决方案,但没有找到。这是我的看法:

Normalizr Laravel Eloquent API Resources

© www.soinside.com 2019 - 2024. All rights reserved.