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 : 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.
	    ];
	}
}
php
pattern
transformers

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

newsletter

A weekly email with the latests articles

support my work

Start trading on binance
  • BTC

    BTC

    18SY81ejLGFuJ9KMWQu5zPrDGuR5rDiauM

  • ETH

    ETH

    0x68e8c828b8ce670062a83199cd8f62667c792f23

  • Monero

    XMR

    895bSneY4eoZjsr2hN2CAALkUrMExHEV5Pbg8TJb6ejnMLN7js1gLAXQySqbSbfzjWHQpQhQpvFtojbkdZQZmM9qCFz7BXU

(adsbygoogle = window.adsbygoogle || []).push({});

2022 © My Dynamic Production SRL All rights Reserved.