Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

A developer friendly wrapper around Fractal

Fractal is an amazing package to transform data before using it in an API. Unfortunately working with Fractal can be a bit verbose. That’s why we created a wrapper called Fractalistic around it, that makes working with Fractal a bit more developer friendly. It’s framework agnostic so you can use it in any PHP project.

Using the vanilla Fractal package data can be transformed like this:

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

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

$manager = new Manager();

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

$manager->parseIncludes('characters');

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

Our Fractalistic wrapper package makes that process a tad easier:

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

There’s also a very short syntax available to quickly transform data:

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 bells and whistles specifically targetted at Laravel users.

To learn all the options Fractalistic has to offer, head over to the readme on GitHub. If you like it, take a look at our previous open source work as well. There’s a list of framework agnostic packages we made on our company site.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band. He loves waffles and butterflies.