Last active
July 6, 2019 15:55
-
-
Save nickalcala/b5c2684c8cc138af409926b3379fea63 to your computer and use it in GitHub Desktop.
Laravel/Lumen API Tutorial - Response transformers with PHP League’s Fractal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use Illuminate\Contracts\Pagination\LengthAwarePaginator; | |
use Illuminate\Http\Request; | |
use Laravel\Lumen\Routing\Controller as BaseController; | |
use League\Fractal\Manager; | |
use League\Fractal\Pagination\IlluminatePaginatorAdapter; | |
use League\Fractal\Resource\Collection; | |
use League\Fractal\Resource\Item; | |
use League\Fractal\Serializer\JsonApiSerializer; | |
class Controller extends BaseController | |
{ | |
/** | |
* @param LengthAwarePaginator $data | |
* @param $transformer | |
* @return array | |
*/ | |
public function paginate($data, $transformer) | |
{ | |
$manager = $this->getFractalManager(); | |
$resource = new Collection($data, $transformer, $transformer->type); | |
$resource->setPaginator(new IlluminatePaginatorAdapter($data)); | |
return $manager->createData($resource)->toArray(); | |
} | |
public function collection($data, $transformer) | |
{ | |
$manager = $this->getFractalManager(); | |
$resource = new Collection($data, $transformer, $transformer->type); | |
return $manager->createData($resource)->toArray(); | |
} | |
public function item($data, $transformer) | |
{ | |
$manager = $this->getFractalManager(); | |
$resource = new Item($data, $transformer, $transformer->type); | |
return $manager->createData($resource)->toArray(); | |
} | |
private function getFractalManager() | |
{ | |
$request = app(Request::class); | |
$manager = new Manager(); | |
$manager->setSerializer(new JsonApiSerializer()); | |
if (!empty($request->query('include'))) { | |
$manager->parseIncludes($request->query('include')); | |
} | |
return $manager; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://niceprogrammer.com/2019/07/06/lumen-api-tutorial-response-transformers-with-php-leagues-fractal/