Table of Contents
Key Points
Installation
Create a database
Create Transformer
Create a controller
Pagination
Includes sub-resources
Emergency Loading
Conclusion
PHP Fractal FAQ
What is PHP Fractal and why it matters?
How does PHP Fractal work?
What is Transformer in PHP Fractal?
What is Serializer in PHP Fractal?
How do I implement PHP Fractal in my project?
Can I use PHP Fractal with any PHP project?
What are the benefits of using PHP Fractal?
How does PHP Fractal compare to other data conversion tools?
Can I customize the output of PHP Fractal?
Where can I learn more about PHP Fractal?
Home Backend Development PHP Tutorial PHP Fractal - Make Your API's JSON Pretty, Always!

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

Feb 10, 2025 am 09:01 AM

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles