jotaen / fractal-response by jotaen

Using Transformers in Laravel Responses
2,962
3
3
Package Data
Maintainer Username: jotaen
Maintainer Contact: jan@jotaen.net (Jan Heuermann)
Package Create Date: 2015-06-03
Package Last Update: 2015-06-10
Language: PHP
License: MIT
Last Refreshed: 2024-12-18 03:05:51
Package Statistics
Total Downloads: 2,962
Monthly Downloads: 1
Daily Downloads: 0
Total Stars: 3
Total Watchers: 3
Total Forks: 0
Total Open Issues: 0

FractalResponse for Laravel

Build Status Scrutinizer Code Quality Latest Release

With FractalReponse you can easily use Fractal Transformers to serialize Laravel Reponse objects.

The FractalResponse class inherits from Illuminate\Http\Response. In addition, you pass your Leage\Fractal-transformer to the with()-method, so that your response gets automatically serialized the way you wish. This is especially helpful when writing REST services, where you have to provide a defined data structure.

Installation:

The easiest way is to add FractalResponse as dependency to your composer.json:

require: {
    "jotaen/fractal-response": "1.x"
}

Example:

<?php namespace App\Http\Controllers;

use League\Fractal;
use Laravel\Lumen\Routing\Controller as BaseController;

use FractalResponse\FractalResponse as Response;

class Controller extends BaseController
{
    public function showOneBook()
    {
      $book = new Book();
      $response = new Response($book, 200);
      $response->with(new BookTransformer());
      return $response;
    }

    public function showSeveralBooks()
    {
      $books = [ new Book(), new Book() ];
      $response = new Response($books, 200);
      $response->with(new BookTransformer());
      return $response;
    }
}


class Book 
{
  public function title() { return 'Help, i am an elephant!'; }
}

class BookTransformer extends Fractal\TransformerAbstract
{
  public function transform($foo)
  {
      return [
          'Title'      => $foo->title(),
      ];
  }
}