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(); // 從數(shù)據(jù)庫(kù)獲取用戶 $users = new Collection($users, $this->userTransformer); // 創(chuàng)建資源集合轉(zhuǎn)換器 $users = $this->fractal->createData($users); // 轉(zhuǎn)換數(shù)據(jù) return $users->toArray(); // 獲取轉(zhuǎn)換后的數(shù)據(jù)數(shù)組 } }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" } // ... ] }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>
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); } }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); } }
$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 ]; } }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(); // 從數(shù)據(jù)庫(kù)獲取用戶 $users = new Collection($users, $this->userTransformer); // 創(chuàng)建資源集合轉(zhuǎn)換器 $users = $this->fractal->createData($users); // 轉(zhuǎn)換數(shù)據(jù) return $users->toArray(); // 獲取轉(zhuǎn)換后的數(shù)據(jù)數(shù)組 } }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" } // ... ] }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>
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

Undress AI Tool
Undress images for free

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

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

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

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
