jotaen/fractal-response

Using Transformers in Laravel Responses

v1.0.0 2015-06-09 21:50 UTC

This package is not auto-updated.

Last update: 2024-10-30 07:58:31 UTC


README

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(),
      ];
  }
}