Transformers in PHP
Another Design Pattern to cover in PHP are the Transformers.
This one is really simple to understand. It allows you to return an object to another format in a re-usable way.
For laravel developers, this is mostly done through Resources.
For other PHP developers, great example can be found here : https://fractal.thephpleague.com/transformers/
For exemple, if you have a database of Cars, and you need to make API requests to a third party service with POST Requests, for example to store a car in an external database. You will want to conform the third party API format. Maybe the car attributes will have different name between your app and the third party. In that case, a Transformer class is very useful.
It'll just be an array where you map the desired attributes formatting with yours.
Very simple example:
<?php
namespace Acme\Transformer;
use Acme\Model\Car;
use League\Fractal;
class CarTransformer
{
public function transform(Car car)
{
return [
'id' => (int) $car->id,
'model_name' => $car->model,
'year' => (int) $car->yr,
// etc.
];
}
}
I consider myself as an IT Business Artisan. Or Consultant CTO. I'm a self-taught Web Developper, coach and teacher. My main work is helping and guiding digital startups.
more about meBTC
bc1qgw9a8hyqqwvcls9ln7vhql4mad0qkveutr2td7
ETH
0x3A720717Da03dB6f3c4a4Ff08BC64100205A79d0
2025 © My Dynamic Production SRL All rights Reserved.