Pages

Saturday, December 23, 2017

Php Generator Trait added to the Waryway Traits Library

Introduction to a Generator Trait

The trait library has grown! The newest addition is the Generator. There are lots of guides online about PHP Generators. Now, a specific 'file line reader' generator is available in the Waryway trait library. Let's take a look at what a generator is, why would it be needed, and an example of how it was implemented.

What is a Generator?

In the context of PHP, a generator is a syntax construct where a function 'yields' a value without instantiating an entire set in memory. Maybe think of it like a magic variable that yield an iteration each time you call it. 

Why would a generator be needed?

In the rare event you need to read from a line based file in PHP, I highly recommend a Generator pattern. It's a quick implementation, and less memory intensive approach to reading from a file. If you need the whole file in memory at one time though, stick with file_get_contents. Essentially, any iterable operation can be conducted with a generator. However, the only time to truly use one, is when only one line at a time is relevant, as opposed to the entire set. An example would be search a file for an entry without sorting it. Just run through the file until the item is found. The complexity is O(n),but the memory footprint is only 1 row.

Example of Implementation

I built a file line reader into a generator as a trait. This can be found in the php-traits-library on github. I like the availability of traits to build a 'base' system without intense inheritance models in PHP (abstract base class, anyone?).  For this trait, it does not cover all generator options, but specifically the line by line file reading approach. I added the typical file reading safety features, but I did not add a terminator - that might actually be a good future idea. What I did add was a callable argument, to allow a closure for parsing the line before return. Passing in a null will just return the line, unprocessed. 

Unit Testing Bonus

I've also built out an example of testing a generator (note: if you are testing something that uses a generator, phpunit has a mock approach for that).

Conclusion

I have as of yet to build out the implementation around the generator. For now - it is in place and ready to go and I've included the latest repo into the service MicroServiceEngine.