blog

Transducers in PHP Made Easy

Have you heard of functional programming, high order functions, etc. before? Probably, right? However, when you hear “transducers”, do you know what those are?

Input/output vector illustration

The Definition of Transducers

We can’t define transducers without talking about reducers first. Quoting Rich Hickey:

A reducing function is just the kind of function you’d pass to reduce – it takes a result so far and a new input and returns the next result-so-far.

A transducer is a function that takes one reducing function and returns another.

Transducers were first introduced into Clojure by Rich Hickey, and ported to PHP by Michael Dowling. Transducers are a powerful way to build algorithmic transformations that you can reuse in many contexts. In this article, we’re going to take a look at how they could be useful through a set of practical examples.

Examples

We need to install the Transducers package via Composer before going any further.

composer require mtdowling/transducers

We’ll use a simple User class for the following examples.

class User
{
    public $id;
    public $name;
    public $age;

    public function __construct($id, $name, $age)
    {
        $this->id = $id;
        $this->name = $name;
        $this->age = $age;
    }

    public function __toString()
    {
        return sprintf("n%d - %s - %d", $this->id, $this->name, $this->age);
    }
}

// demo data
$data = [
    new User(1, "younes", 24),
    new User(2, "youssef", 26),
    new User(3, "hamza", 25),
    new User(4, "ismail", 17),
];
use Transducers as t;

$uppercase = tmap(function($user) { 
    return new User($user->id, ucfirst($user->name), $user->age); 
});

$result = txform($data, $uppercase);

var_dump($result);

Continue reading %Transducers in PHP Made Easy%

LEAVE A REPLY