Transformers in PHP

profile picture

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 :

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:

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.

about me

profile picture

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 me

follow me


A weekly email with the latests articles

support my work

Start trading on binance
  • BTC



  • ETH



  • Monero



2024 © My Dynamic Production SRL All rights Reserved.