Table of Contents
What is the basic concept of Transducers in PHP?
How is Transducers different from traditional PHP functions?
Can you provide an example of Transducer in PHP?
How to use Transducers with different data sources?
What are the benefits of using Transducers in PHP?
What are the disadvantages of using Transducers in PHP?
Can Transducers be used with PHP frameworks?
How to learn more about Transducers in PHP?
Does Transducers be used in other programming languages?
Can I use Transducers with PHP built-in array functions?
Home Backend Development PHP Tutorial Transducers in PHP Made Easy

Transducers in PHP Made Easy

Feb 15, 2025 am 11:36 AM

In-depth PHP functional programming: Exploring Transducers

You may have heard of functional programming and advanced functions, but do you know Transducers? This article will take you to explore this powerful data conversion tool.

Transducers in PHP Made Easy

Core points:

  • Transducers originated from Clojure and ported to PHP by Michael Dowling, is a powerful way to build reusable algorithm transformations. They are functions that accept one reduction function and return another reduction function.
  • PHP's Transducers package allows data to be converted in a variety of ways, such as capitalizing the initials of names or removing minors from user lists. Transformations can be combined into a single Transducer for reuse.
  • The reduction function in Transducer receives a value as a parameter and returns an array of reduction functions containing three elements: "init" (init), "result" (final result), and "step" (reduce) logic).
  • The advantage of Transducers is that it separates the data conversion process from the actual data source, making the code more modular and easier to maintain. They allow the creation of reusable software components that can be used in any data source. However, due to their functional programming roots, they may be more complex than traditional PHP functions.

Transducers definition

To understand Transducers, you first need to understand Reducers. Quoting Rich Hickey:

A reduction function is exactly the type of function you pass to reduce - it receives the result so far and a new input and returns the next so far result.

A Transducer is a function that receives one reduction function and returns another reduction function.

Transducers were initially introduced to Clojure by Rich Hickey and ported to PHP by Michael Dowling. Transducers are a powerful way to build algorithmic transformations that can be reused in a variety of situations. This article will explore its use through a series of practical examples.

Example

Before proceeding, we need to install the Transducers package through Composer.

1

composer require mtdowling/transducers

Copy after login
Copy after login
Copy after login

We will use a simple User class for the following example.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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);

    }

}

 

// 示例数据

$data = [

    new User(1, "younes", 24),

    new User(2, "youssef", 26),

    new User(3, "hamza", 25),

    new User(4, "ismail", 17),

];

Copy after login
Copy after login

1

2

3

4

5

6

7

8

9

use Transducers as t;

 

$uppercase = t\map(function($user) {

    return new User($user->id, ucfirst($user->name), $user->age);

});

 

$result = t\xform($data, $uppercase);

 

var_dump($result);

Copy after login
Copy after login
The

map function is similar to the array_map function of PHP: we pass a callable function, which in this case will capitalize the username initial.

We use the xform function to apply our uppercase Transducer. It takes our data as the first parameter and the Transducer as the second parameter.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

// 输出

array(4) {

  [0]=>

  object(User)#14 (3) {

    ["id"]=>

    int(1)

    ["name"]=>

    string(6) "Younes"

    ["age"]=>

    int(24)

  }

  [1]=>

  object(User)#15 (3) {

    ["id"]=>

    int(2)

    ["name"]=>

    string(7) "Youssef"

    ["age"]=>

    int(26)

  }

  [2]=>

  object(User)#16 (3) {

    ["id"]=>

    int(3)

    ["name"]=>

    string(5) "Hamza"

    ["age"]=>

    int(25)

  }

  [3]=>

  object(User)#17 (3) {

    ["id"]=>

    int(4)

    ["name"]=>

    string(6) "Ismail"

    ["age"]=>

    int(17)

  }

}

Copy after login
Copy after login

xform Returns a value of the same type as the data parameter (in this case an array). If you strictly need to output an array, we can also use to_array.

1

2

3

// ...

$result = t\to_array($data, $uppercase);

// ...

Copy after login
Copy after login

We can also use to_string to convert the output to a string, or use into($target, $coll, callable $xf) to convert the output to a specific type. For more details, please see the documentation.

1

composer require mtdowling/transducers

Copy after login
Copy after login
Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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);

    }

}

 

// 示例数据

$data = [

    new User(1, "younes", 24),

    new User(2, "youssef", 26),

    new User(3, "hamza", 25),

    new User(4, "ismail", 17),

];

Copy after login
Copy after login

The best part about Transducers is that we can combine multiple conversions into one Transducer. For example, let's capitalize the initial letter of the username and delete the minor.

1

2

3

4

5

6

7

8

9

use Transducers as t;

 

$uppercase = t\map(function($user) {

    return new User($user->id, ucfirst($user->name), $user->age);

});

 

$result = t\xform($data, $uppercase);

 

var_dump($result);

Copy after login
Copy after login
The

filter function is similar to the array_filter function of PHP. The comp function creates a Transducer from the Transducer list, in this case uppercase (using map) and removeMinors (using filter).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

// 输出

array(4) {

  [0]=>

  object(User)#14 (3) {

    ["id"]=>

    int(1)

    ["name"]=>

    string(6) "Younes"

    ["age"]=>

    int(24)

  }

  [1]=>

  object(User)#15 (3) {

    ["id"]=>

    int(2)

    ["name"]=>

    string(7) "Youssef"

    ["age"]=>

    int(26)

  }

  [2]=>

  object(User)#16 (3) {

    ["id"]=>

    int(3)

    ["name"]=>

    string(5) "Hamza"

    ["age"]=>

    int(25)

  }

  [3]=>

  object(User)#17 (3) {

    ["id"]=>

    int(4)

    ["name"]=>

    string(6) "Ismail"

    ["age"]=>

    int(17)

  }

}

Copy after login
Copy after login

Now we have a reusable Transducer combination that we can use at any time to reduce data based on this standard. Check the documentation for a list of available reduction functions.

Create Transducer

The reduction function receives a value as a parameter and returns an array of reduction functions that must contain three elements:

  • init: Function that returns the initial value of Transducer. If no initial value is provided, it is called only on the first call.
  • result:result function is used to build the final result from the call stack.
  • step: This is where you write the reduction logic—you may call it zero or multiple times according to your reduction logic.

This gets very confusing without actual code, so let's take the take Transducer function as an example. It gets n items from the top of the data array.

1

2

3

// ...

$result = t\to_array($data, $uppercase);

// ...

Copy after login
Copy after login

1

2

3

4

5

6

7

8

9

use Transducers as t;

 

$uppercase = t\map(function($user) {

    return new User($user->id, ucfirst($user->name), $user->age);

});

 

$result = t\to_string($data, $uppercase);

 

var_dump($result);

Copy after login

The following is the source code of the take reduction function.

1

2

3

4

5

6

// 输出

string(64) "

1 - Younes - 24

2 - Youssef - 26

3 - Hamza - 25

4 - Ismail - 17"

Copy after login
The

take function is called multiple times with result and input parameters. Each time it is called, it decrements the remaining variable and tests whether it is less than zero. In this case, we return a Reduced object instance, which represents a stop point.

Our Transducer function example will remove empty elements from the data. Using the previous explanation of how Transducer works, we can access the $input variable and decide whether to call the next step callback or simply return the value.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

$uppercase = t\map(function($user) {

    return new User($user->id, ucfirst($user->name), $user->age);

});

$removeMinors = t\filter(function($user) {

    return $user->age >= 18;

});

 

$comp = t\comp(

    $uppercase,

    $removeMinors

);

 

$result = t\to_string($data, $comp);

 

var_dump($result);

Copy after login

We can test this by adding some empty items to our $data variable.

1

2

3

4

5

// 输出

string(48) "

1 - Younes - 24

2 - Youssef - 26

3 - Hamza - 25"

Copy after login

1

2

3

4

5

6

7

8

9

10

// ....

$comp = t\comp(

    $uppercase,

    $removeMinors,

    t\take(2)

);

 

$result = t\to_string($data, $comp);

 

var_dump($result);

Copy after login

Conclusion

In this article, we understand a new aspect of the functional programming world called Transducers. We review the purpose of Transducers, even if data conversion is easier. We also reviewed some examples to better demonstrate the value of Transducers. You now have a new tool in your developer toolbox, or at least have a better understanding of the concept of Transducer.

If you have any questions about Transducers, you can post it below!

FAQs about Transducers in PHP

What is the basic concept of Transducers in PHP?

Transducers in PHP is a data processing technology that allows you to create composable and reusable software components. They are essentially functions that accept a reducer and return a new reducer. This concept is borrowed from Clojure and JavaScript and has adapted to PHP. Transducers allow you to separate the data conversion process from the actual data source, making your code more modular and easier to maintain.

How is Transducers different from traditional PHP functions?

Traditional PHP functions usually combine the process of getting and converting data, which can make code difficult to maintain and reuse. Transducers, on the other hand, separate the two processes. This means you can create a Transducer that converts data in a specific way and then use it with any data source to make your code more flexible and reusable.

Can you provide an example of Transducer in PHP?

Of course, let's consider a simple example. Suppose you have an array of numbers and you want to add 1 to each number. You can create a Transducer that does this:

1

composer require mtdowling/transducers

Copy after login
Copy after login
Copy after login

You can then use this Transducer with any reduction function and data source.

How to use Transducers with different data sources?

Transducers are designed to be used with any data source. This is because they run at the single data item level, not at the entire data source level. Therefore, you can use Transducer with arrays, database query results, data streams from network connections, etc. The only requirement is that your data source must be able to work with the reduction function.

What are the benefits of using Transducers in PHP?

Transducers offer many benefits. They allow you to separate the data conversion process from the actual data source, making your code more modular and easier to maintain. They also allow you to create reusable software components that can be used in any data source. Finally, because Transducers operate on a single data item, they may be more efficient than traditional PHP functions when dealing with large data sets.

What are the disadvantages of using Transducers in PHP?

While Transducers provide many benefits, they may also be more complex than traditional PHP functions. This is because they involve the concepts of functional programming that may not be familiar to some PHP developers. But once you understand how Transducers work, they can be a powerful tool for writing clean, efficient and reusable code.

Can Transducers be used with PHP frameworks?

Yes, Transducers can be used with any PHP framework. They are a general data processing technology that does not depend on any specific framework features. However, some frameworks may provide their own utilities for handling Transducers, which can make them easier to use.

How to learn more about Transducers in PHP?

There are many resources available to learn Transducers in PHP. You can start by reading online articles and tutorials, such as articles on SitePoint. There are also books and online courses that cover the topic in more depth. Finally, you can try writing your own Transducers and using them in your PHP project.

Does Transducers be used in other programming languages?

Yes, the concept of Transducers originated from the Clojure programming language and has since been adopted by several other languages, including JavaScript and PHP. Each language implements Transducers in its own way, but the basic concepts are the same.

Can I use Transducers with PHP built-in array functions?

Yes, you can use Transducers with PHP's built-in array functions. However, remember that these functions may not be as efficient as using Transducer, especially when dealing with large arrays. This is because PHP's array functions usually create new arrays, and Transducer can convert data in place.

The above is the detailed content of Transducers in PHP Made Easy. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles