2017 © Pedro Peláez
 

library fractalistic

A developer friendly wrapper around Fractal

image

spatie/fractalistic

A developer friendly wrapper around Fractal

  • Monday, January 15, 2018
  • by Spatie
  • Repository
  • 6 Watchers
  • 214 Stars
  • 715,135 Installations
  • PHP
  • 5 Dependents
  • 0 Suggesters
  • 24 Forks
  • 0 Open issues
  • 19 Versions
  • 18 % Grown

The README.md

, (*1)

A developer friendly wrapper around Fractal

Latest Version on Packagist Software License GitHub Workflow Status Quality Score Total Downloads, (*2)

Fractal is an amazing package to transform data before using it in an API. Unfortunately working with Fractal can be a bit verbose., (*3)

Using Fractal data can be transformed like this:, (*4)

use League\Fractal\Manager;
use League\Fractal\Resource\Collection;

$books = [
   ['id'=>1, 'title'=>'Hogfather', 'characters' => [...]], 
   ['id'=>2, 'title'=>'Game Of Thrones', 'characters' => [...]]
];

$manager = new Manager();

$resource = new Collection($books, new BookTransformer());

$manager->parseIncludes('characters');

$manager->createData($resource)->toArray();

This package makes that process a tad easier:, (*5)

Fractal::create()
   ->collection($books)
   ->transformWith(new BookTransformer())
   ->includeCharacters()
   ->toArray();

There's also a very short syntax available to quickly transform data:, (*6)

Fractal::create($books, new BookTransformer())->toArray();

If you want to use this package inside Laravel, it's recommend to use laravel-fractal instead. That package contains a few more whistles and bells specifically targetted at Laravel users., (*7)

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website., (*8)

Support us

, (*9)

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products., (*10)

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall., (*11)

Install

You can pull in the package via composer:, (*12)

``` bash composer require spatie/fractalistic, (*13)


## Usage In the following examples were going to use the following array as example input: ```php $books = [['id'=>1, 'title'=>'Hogfather'], ['id'=>2, 'title'=>'Game Of Kill Everyone']];

But know that any structure that can be looped (for instance a collection) can be used., (*14)

Let's start with a simple transformation., (*15)

Spatie\Fractalistic\Fractal::create()
   ->collection($books)
   ->transformWith(function($book) { return ['id' => $book['id']];})
   ->toArray();

This will return:, (*16)

['data' => [['id' => 1], ['id' => 2]]

In all following examples it's assumed that you imported the Spatie\Fractalistic\Fractal at the top of your php file., (*17)

Instead of using a closure you can also pass a Transformer:, (*18)

Fractal::create()
   ->collection($books)
   ->transformWith(new BookTransformer())
   ->toArray();

You can also pass the classname of the Transformer:, (*19)

Fractal::create()
   ->collection($books)
   ->transformWith(BookTransformer::class)
   ->toArray();

To make your code a bit shorter you could also pass the transform closure, class, or classname as a second parameter of the collection-method:, (*20)

Fractal::create()->collection($books, new BookTransformer())->toArray();

Want to get some sweet json output instead of an array? No problem!, (*21)

Fractal::create()->collection($books, new BookTransformer())->toJson();

A single item can also be transformed:, (*22)

Fractal::create()->item($books[0], new BookTransformer())->toArray();

Using a serializer

Let's take a look again at the output of the first example:, (*23)

['data' => [['id' => 1], ['id' => 2]];

Notice that data-key? That's part of Fractal's default behaviour. Take a look at Fractals's documentation on serializers to find out why that happens., (*24)

If you want to use another serializer you can specify one with the serializeWith-method. The Spatie\Fractalistic\ArraySerializer comes out of the box. It removes the data namespace for both collections and items., (*25)

Fractal::create()
   ->collection($books)
   ->transformWith(function($book) { return ['id' => $book['id']];})
   ->serializeWith(new \Spatie\Fractalistic\ArraySerializer())
   ->toArray();

//returns [['id' => 1], ['id' => 2]]

You can also pass the serializer classname instead of an instantiation:, (*26)

Fractal::create()
   ->collection($books)
   ->transformWith(BookTransformer::class)
   ->serializeWith(MySerializer::class)
   ->toArray();

Changing the default serializer

You can change the default serializer by providing the classname or an instantiation of your favorite serializer in the config file., (*27)

Using includes

Fractal provides support for optionally including data on the relationships for the data you're exporting. You can use Fractal's parseIncludes which accepts a string or an array:, (*28)

Fractal::create()
   ->collection($this->testBooks, new TestTransformer())
   ->parseIncludes(['characters', 'publisher'])
   ->toArray();

To improve readablity you can also use a function named include followed by the name of the include you want to... include:, (*29)

Fractal::create()
   ->collection($this->testBooks, new TestTransformer())
   ->includeCharacters()
   ->includePublisher()
   ->toArray();

Using excludes

Similar to includes Fractal also provides support for optionally excluding data on the relationships for the data you're exporting. You can use Fractal's parseExcludes which accepts a string or an array:, (*30)

Fractal::create()
   ->collection($this->testBooks, new TestTransformer())
   ->parseExcludes(['characters', 'publisher'])
   ->toArray();

To improve readability you can also use a function named exclude followed by the name of the include you want to... exclude:, (*31)

Fractal::create()
   ->collection($this->testBooks, new TestTransformer())
   ->excludeCharacters()
   ->excludePublisher()
   ->toArray();

Including meta data

Fractal has support for including meta data. You can use addMeta which accepts one or more arrays:, (*32)

Fractal::create()
   ->collection($this->testBooks, function($book) { return ['name' => $book['name']];})
   ->addMeta(['key1' => 'value1'], ['key2' => 'value2'])
   ->toArray();

This will return the following array:, (*33)

[
   'data' => [
        ['title' => 'Hogfather'],
        ['title' => 'Game Of Thrones'],
    ],
   'meta' => [
        ['key1' => 'value1'], 
        ['key2' => 'value2'],
    ]
];

Using pagination

Fractal provides a Laravel-specific paginator, IlluminatePaginatorAdapter, which accepts an instance of Laravel's LengthAwarePaginator and works with paginated Eloquent results. When using some serializers, such as the JsonApiSerializer, pagination data can be automatically generated and included in the result set:, (*34)

$paginator = Book::paginate(5);
$books = $paginator->getCollection();

Fractal::create()
    ->collection($books, new TestTransformer())
    ->serializeWith(new JsonApiSerializer())
    ->paginateWith(new IlluminatePaginatorAdapter($paginator))
    ->toArray();

Using a cursor

Fractal provides a simple cursor class, League\Fractal\Pagination\Cursor. You can use any other cursor class as long as it implements the League\Fractal\Pagination\CursorInterface interface. When using it, the cursor information will be automatically included in the result metadata:, (*35)

$books = $paginator->getCollection();

$currentCursor = 0;
$previousCursor = null;
$count = count($books);
$newCursor = $currentCursor + $count;

Fractal::create()
  ->collection($books, new TestTransformer())
  ->serializeWith(new JsonApiSerializer())
  ->withCursor(new Cursor($currentCursor, $previousCursor, $newCursor, $count))
  ->toArray();

Setting a custom resource name

Certain serializers wrap the array output with a data element. The name of this element can be customized:, (*36)

Fractal::create()
    ->collection($this->testBooks, new TestTransformer())
    ->serializeWith(new ArraySerializer())
    ->withResourceName('books')
    ->toArray();
Fractal::create()
    ->item($this->testBooks[0], new TestTransformer(), 'book')
    ->serializeWith(new ArraySerializer())
    ->toArray();

Limit recursion

To increase or decrease the level of embedded includes you can use limitRecursion., (*37)

php Fractal::create() ->collection($this->testBooks, new TestTransformer()) ->includesDataThatHasALotOfRecursion ->limitRecursion(5);, (*38)

If you do not call limitRecursion a default value of 10 is used., (*39)

Quickly transform data with the short function syntax

You can also pass arguments to the fractal-function itself. The first arguments should be the data you which to transform. The second one should be a transformer or a closure that will be used to transform the data. The third one should be a serializer., (*40)

Here are some examples, (*41)

Fractal::create($books, new BookTransformer())->toArray();

Fractal::create($books, new BookTransformer(), new ArraySerializer())->toArray();

Fractal::create($books, BookTransformer::class, ArraySerializer::class)->toArray();

Fractal::create(['item1', 'item2'], function ($item) {
   return $item . '-transformed';
})->toArray();

Changelog

Please see CHANGELOG for more information what has changed recently., (*42)

Testing

bash $ composer test, (*43)

Contributing

Please see CONTRIBUTING for details., (*44)

Security

If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker., (*45)

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using., (*46)

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium., (*47)

We publish all received postcards on our company website., (*48)

Credits

License

The MIT License (MIT). Please see License File for more information., (*49)

The Versions

15/01 2018

dev-master

9999999-dev https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

15/01 2018

2.7.1

2.7.1.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

08/09 2017

dev-analysis-Xa4j70

dev-analysis-Xa4j70 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

08/09 2017

2.7.0

2.7.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

06/09 2017

2.6.0

2.6.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

19/08 2017

2.5.0

2.5.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

19/08 2017

2.4.0

2.4.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

24/07 2017

2.3.2

2.3.2.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

22/07 2017

2.3.1

2.3.1.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

03/07 2017

2.3.0

2.3.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

29/05 2017

2.2.0

2.2.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

10/05 2017

2.1.1

2.1.1.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

04/05 2017

2.1.0

2.1.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

26/04 2017

2.0.0

2.0.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

26/04 2017

dev-analysis-Xa57KV

dev-analysis-Xa57KV https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

19/01 2017

1.0.2

1.0.2.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

02/01 2017

1.0.1

1.0.1.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

09/12 2016

1.0.0

1.0.0.0 https://github.com/spatie/fractalistic

A developer friendly wrapper around Fractal

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic

09/12 2016

0.0.1

0.0.1.0 https://github.com/spatie/fractalistic

Making working with Fractal a breeze

  Sources   Download

MIT

The Requires

 

The Development Requires

api transform spatie fractal fractalistic