Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Mark Baker:
A Functional Guide to Cat Herding with PHP Generators
Jan 19, 2016 @ 16:05:13

In this post to his blog Mark Baker looks at a feature added in PHP 5.5 - generators - and how to use them with some of the array handling functionality PHP provides.

When working with arrays in PHP, three of the most useful functions available to us are array_map(), array_filter() and array_reduce().

[...] However, these functions only work with standard PHP arrays; so if we are using Generators as a data source instead of an array, then we can’t take advantage of the functionality that they provide. Fortunately, it’s very easy to emulate that functionality and apply it to Generators (and also to other Traversable objects like SPL Iterators), giving us access to all of the flexibility and power that mapping, filtering and reducing can offer.

He starts with a more "real world" example of using a generator in a handler for GPX files, XML files storing GPS data. He gives an example of the typical file contents and shows a simple generator script (class) that he uses to grab chunks of the file at a time instead of reading it all in and parsing it from there. He then uses this generator along with a bit of extra handling to mimic array filtering, transformation and reducing the data being returned.

tagged: functional generator tutorial array filter reduce transformation

Link: http://markbakeruk.net/2016/01/19/a-functional-guide-to-cat-herding-with-php-generators/


Trending Topics: