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.
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>
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); } }
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 ]; } }
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" } // ... ] }
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.
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>
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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!