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.
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>
or
<code>composer create-project laravel/laravel demo</code>
Then, within the folder, we need the Fractal package.
<code>composer require league/fractal</code>
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); } }
// 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); } }
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 ]; } }
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 ]; } }
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(); // 获取转换后的数据数组 } }
{ "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" } // ... ] }
Pagination
Laravel tends to simplify things. We can implement pagination like this:
<code>laravel new demo</code>
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>
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>
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); } }
$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); } }
$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 ]; } }
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 ]; } }
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(); // 获取转换后的数据数组 } }
{ "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" } // ... ] }
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>
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>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

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,

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.

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? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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

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...

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.
