Home > Backend Development > PHP Tutorial > PHP Fractal - Make Your API's JSON Pretty, Always!

PHP Fractal - Make Your API's JSON Pretty, Always!

Lisa Kudrow
Release: 2025-02-10 09:01:09
Original
421 people have browsed it

PHP Fractal - Make Your API's JSON Pretty, Always!

This article was peer-reviewed by Viraj Khatavkar. Thanks to all the peer reviewers of SitePoint for getting SitePoint content to its best!


If you have built the API before, I bet you are used to outputting the data directly as a response. This may not be harmful if it is done correctly, but there are some practical alternatives that can help solve this problem.

One of the available solutions is Fractal. It allows us to create a new transformation layer for the model before returning the model as a response. It is very flexible and easy to integrate into any application or framework.

PHP Fractal - Make Your API's JSON Pretty, Always!

Key Points

  • PHP Fractal is a solution that allows developers to create new transformation layers for their models before returning them as responses, making JSON data easier to manage and consistent.
  • Fractal is flexible and easy to integrate into any application or framework. It works by using Transformer to convert complex data structures into simpler formats and using Serializer to format the final output.
  • Fractal also allows the inclusion of sub-resources (relationships) into the response when requested by the user, adding another layer of flexibility and control to data rendering.
  • Using Fractal can optimize query performance by loading relationships at one time, thus solving the n 1 problems that Eloquent lazy loading often encounters.

Installation

We will use the Laravel 5.3 application to build the example and integrate the Fractal package with it, so go ahead and use the installer or create a new Laravel application via Composer.

<code>laravel new demo</code>
Copy after login
Copy after login
Copy after login

or

<code>composer create-project laravel/laravel demo</code>
Copy after login
Copy after login
Copy after login

Then, within the folder, we need the Fractal package.

<code>composer require league/fractal</code>
Copy after login
Copy after login

Create a database

Our database contains users and roles tables. Each user has a role and each role has a permission list.

// app/User.php

class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
        'role_id',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class);
    }
}
Copy after login
Copy after login
// app/Role.php

class Role extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'permissions'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function users()
    {
        return $this->hasMany(User::class);
    }
}
Copy after login
Copy after login

Create Transformer

We will create a Transformer for each model. Our UserTransformer class looks like this:

// app/Transformers/UserTransformer.php

namespace App\Transformers;

use App\User;
use League\Fractal\TransformerAbstract;

class UserTransformer extends TransformerAbstract
{
    public function transform(User $user)
    {
        return [
            'name' => $user->name,
            'email' => $user->email
        ];
    }
}
Copy after login
Copy after login

Yes, creating a Transformer is that simple! It just converts data in a way that developers can manage, not leave it to the ORM or repository.

We extend the TransformerAbstract class and define the transform method, which will be called using the User instance. The same is true for the RoleTransformer class.

namespace App\Transformers;

use App\Role;
use League\Fractal\TransformerAbstract;

class RoleTransformer extends TransformerAbstract
{
    public function transform(Role $role)
    {
        return [
            'name' => $role->name,
            'slug' => $role->slug,
            'permissions' => $role->permissions
        ];
    }
}
Copy after login
Copy after login

Create a controller

Our controllers should convert data before sending it back to the user. We will now handle the UsersController class, and temporarily define only the index and show operations.

// app/Http/Controllers/UsersController.php

class UsersController extends Controller
{
    /**
     * @var Manager
     */
    private $fractal;

    /**
     * @var UserTransformer
     */
    private $userTransformer;

    function __construct(Manager $fractal, UserTransformer $userTransformer)
    {
        $this->fractal = $fractal;
        $this->userTransformer = $userTransformer;
    }

    public function index(Request $request)
    {
        $users = User::all(); // 从数据库获取用户
        $users = new Collection($users, $this->userTransformer); // 创建资源集合转换器
        $users = $this->fractal->createData($users); // 转换数据

        return $users->toArray(); // 获取转换后的数据数组
    }
}
Copy after login
Copy after login
The index operation will query all users from the database, create a collection of resources using the user list and converter, and then perform the actual conversion process.

{
  "data": [
    {
      "name": "Nyasia Keeling",
      "email": "crooks.maurice@example.net"
    },
    {
      "name": "Laron Olson",
      "email": "helen55@example.com"
    },
    {
      "name": "Prof. Fanny Dach III",
      "email": "edgardo13@example.net"
    },
    {
      "name": "Athena Olson Sr.",
      "email": "halvorson.jules@example.com"
    }
    // ...
  ]
}
Copy after login
Copy after login
Of course, it doesn't make sense to return all users at once, and we should implement the pager for this.

Pagination

Laravel tends to simplify things. We can implement pagination like this:

<code>laravel new demo</code>
Copy after login
Copy after login
Copy after login

But in order for this to work with Fractal, we may need to add some code to convert the data and then call the pager.

<code>composer create-project laravel/laravel demo</code>
Copy after login
Copy after login
Copy after login

The first step is to paginate the data from the model. Next, we create a resource collection as before and then set up a pager on the collection.

Fractal provides Laravel with a paginator adapter to convert the LengthAwarePaginator class, which also provides an adapter for Symfony and Zend.

<code>composer require league/fractal</code>
Copy after login
Copy after login

Note that it adds extra fields to the paging details. You can read more about paging in the documentation.

Includes sub-resources

Now that we are familiar with Fractal, it is time to learn how to include subresources (relationships) into the response when a user requests.

We can request to include additional resources into the response, for example http://demo.vaprobash.dev/users?include=role. Our converter can automatically detect what is being requested and parse the include parameter.

// app/User.php

class User extends Authenticatable
{
    protected $fillable = [
        'name',
        'email',
        'password',
        'role_id',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class);
    }
}
Copy after login
Copy after login
The

$availableIncludes property tells the converter that we may need to include some extra data into the response. If the include query parameter requests the user role, it will call the includeRole method.

// app/Role.php

class Role extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'permissions'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function users()
    {
        return $this->hasMany(User::class);
    }
}
Copy after login
Copy after login

$this->fractal->parseIncludes line is responsible for parsing include query parameters. If we request a list of users, we should see something like this:

// app/Transformers/UserTransformer.php

namespace App\Transformers;

use App\User;
use League\Fractal\TransformerAbstract;

class UserTransformer extends TransformerAbstract
{
    public function transform(User $user)
    {
        return [
            'name' => $user->name,
            'email' => $user->email
        ];
    }
}
Copy after login
Copy after login

If each user has a role list, we can change the converter to something like this:

namespace App\Transformers;

use App\Role;
use League\Fractal\TransformerAbstract;

class RoleTransformer extends TransformerAbstract
{
    public function transform(Role $role)
    {
        return [
            'name' => $role->name,
            'slug' => $role->slug,
            'permissions' => $role->permissions
        ];
    }
}
Copy after login
Copy after login
When

contains subresources, we can use point notation to nest relationships. Suppose each role has a list of permissions stored in a separate table and we want to list users with their roles and permissions. We can do include=role.permissions.

Sometimes, we need to include some necessary associations by default, such as address associations. We can do this by using the $defaultIncludes property in the converter.

// app/Http/Controllers/UsersController.php

class UsersController extends Controller
{
    /**
     * @var Manager
     */
    private $fractal;

    /**
     * @var UserTransformer
     */
    private $userTransformer;

    function __construct(Manager $fractal, UserTransformer $userTransformer)
    {
        $this->fractal = $fractal;
        $this->userTransformer = $userTransformer;
    }

    public function index(Request $request)
    {
        $users = User::all(); // 从数据库获取用户
        $users = new Collection($users, $this->userTransformer); // 创建资源集合转换器
        $users = $this->fractal->createData($users); // 转换数据

        return $users->toArray(); // 获取转换后的数据数组
    }
}
Copy after login
Copy after login
One of my favorite things about the Fractal package is the ability to pass parameters to include parameters. A good example in the documentation is sorting in order. We can apply it to our example as follows:

{
  "data": [
    {
      "name": "Nyasia Keeling",
      "email": "crooks.maurice@example.net"
    },
    {
      "name": "Laron Olson",
      "email": "helen55@example.com"
    },
    {
      "name": "Prof. Fanny Dach III",
      "email": "edgardo13@example.net"
    },
    {
      "name": "Athena Olson Sr.",
      "email": "halvorson.jules@example.com"
    }
    // ...
  ]
}
Copy after login
Copy after login
The important part here is list($orderCol, $orderBy) = $paramBag->get('order') ?: ['created_at', 'desc'];, which will try to get the order parameter from the user include and apply it to the query builder.

We can now sort the included user lists in order by passing parameters (/roles?include=users:order(name|asc)). You can read more about including resources in the documentation.

But what happens if the user does not have any associated roles? It will stop and an error appears because it expects valid data instead of null. Let's remove the relationship from the response instead of displaying its null value.

<code>laravel new demo</code>
Copy after login
Copy after login
Copy after login

Emergency Loading

Because Eloquent delays loading the model when accessing it, we may encounter n 1 problems. This can be solved by a one-time eager loading relationship to optimize queries.

<code>composer create-project laravel/laravel demo</code>
Copy after login
Copy after login
Copy after login

This way, we will not have any additional queries when accessing the model relationship.

Conclusion

I stumbled upon Fractal while reading "Building an API You Won't Hate" by Phil Sturgeon, a great and informative read that I highly recommend.

Did you use a converter when building your API? Do you have any preferred package that does the same work, or are you just using json_encode? Please let us know in the comment section below!

PHP Fractal FAQ

What is PHP Fractal and why it matters?

PHP Fractal is a powerful tool that helps render and transform data for the API. It is important because it provides a standardized way to output complex, nested data structures, ensuring that the API's data output is consistent, well-structured, and easy to understand. This makes it easier for developers to use your API and reduces the possibility of errors.

How does PHP Fractal work?

PHP Fractal works by taking complex data structures and converting them into easier-to-use formats. It is implemented through two main components: Transformer and Serializer. Transformer is responsible for converting complex data into simpler formats, while Serializer formats the final output.

What is Transformer in PHP Fractal?

The Transformer in PHP Fractal is a class that defines how application data should be output in the API response. They take complex data structures and convert them into simpler, easier to use formats. This allows you to precisely control what data is included in the API response and how it is structured.

What is Serializer in PHP Fractal?

Serializer in PHP Fractal is responsible for formatting the final output of the API. They take the data that has been converted by Transformer and format it into a specific structure. This allows you to ensure that the output of the API is consistent and easy to understand.

How do I implement PHP Fractal in my project?

Implementing PHP Fractal in a project involves installing the Fractal library through Composer, creating a Transformer for the data, and then using the Fractal class to transform the data using Transformer. You can then use one of Fractal's Serializers to output the converted data.

Can I use PHP Fractal with any PHP project?

Yes, PHP Fractal is a standalone library that can be used with any PHP project. It does not rely on any specific framework or platform, which makes it a universal tool for any PHP developer.

What are the benefits of using PHP Fractal?

Using PHP Fractal provides many benefits. It ensures that the output of the API is consistent and well-structured, making it easier for developers to use. It also provides a standardized way to transform complex data structures, reducing the possibility of errors and making the code easier to maintain.

How does PHP Fractal compare to other data conversion tools?

PHP Fractal stands out for its simplicity and flexibility. It provides a straightforward way to transform complex data structures, and it allows for high customization using Transformer and Serializer. This makes it a powerful tool for any developer who uses APIs.

Can I customize the output of PHP Fractal?

Yes, PHP Fractal is highly customizable. You can create custom Transformers to accurately control how your data is converted, and you can format the output in different ways using different Serializers. This allows you to adjust the output of your API to your specific needs.

Where can I learn more about PHP Fractal?

There are many resources to help you learn more about PHP Fractal. The official PHP League website provides comprehensive documentation and there are many tutorials and blog posts online. Additionally, the PHP Fractal GitHub repository is a great place to explore the code and see examples of how it is used.

The above is the detailed content of PHP Fractal - Make Your API's JSON Pretty, Always!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template