|
| 1 | +# PHPStreams |
| 2 | + |
| 3 | +[](https://packagist.org/packages/bertptrs/phpstreams) [](https://packagist.org/packages/bertptrs/phpstreams) [](https://packagist.org/packages/bertptrs/phpstreams) [](https://travis-ci.org/bertptrs/phpstreams) |
| 4 | + |
| 5 | +A partial implementation of the Java 8 Streams API in PHP. PHPStreams |
| 6 | +can use your generators, your arrays and really anything that is |
| 7 | +[Iterable](https://wiki.php.net/rfc/iterable) and convert modify it like |
| 8 | +you're used to using Java Streams! |
| 9 | + |
| 10 | +Using streams and generators, you can easily sort through large amounts |
| 11 | +of data without having to have it all in memory or in scope. Streams |
| 12 | +also make it easier to structure your code, by (more or less) enforcing |
| 13 | +single resposibility. |
| 14 | + |
| 15 | +The library is compatible with PHP 5.5.9 and up. |
| 16 | + |
| 17 | +## Installation |
| 18 | + |
| 19 | +PHPStreams can be installed using Composer. Just run `composer require |
| 20 | +bertptrs/phpstreams` in your project root! |
| 21 | + |
| 22 | +## Usage |
| 23 | + |
| 24 | +Using streams is easy. Say, we want the first 7 odd numbers in the |
| 25 | +Fibonacci sequence. To do this using Streams, we do the following: |
| 26 | + |
| 27 | +```php |
| 28 | +// Define a generator for Fibonacci numbers |
| 29 | +function fibonacci() |
| 30 | +{ |
| 31 | + yield 0; |
| 32 | + yield 1; |
| 33 | + |
| 34 | + $prev = 0; |
| 35 | + $cur = 1; |
| 36 | + |
| 37 | + while (true) { |
| 38 | + yield ($new = $cur + $prev); |
| 39 | + $prev = $cur; |
| 40 | + $cur = $new; |
| 41 | + } |
| 42 | +}; |
| 43 | + |
| 44 | +// Define a predicate that checks for odd numbers |
| 45 | +$isOdd = function($num) { |
| 46 | + return $num % 2 == 1; |
| 47 | +}; |
| 48 | + |
| 49 | +// Create our stream. |
| 50 | +$stream = new phpstreams\Stream(fibonacci()); |
| 51 | + |
| 52 | +// Finally, use these to create our result. |
| 53 | +$oddFibo = $stream->filter($isOdd) // Keep only the odd numbers |
| 54 | + ->limit(8) // Limit our results |
| 55 | + ->toArray(false); // Convert to array, discarding keys |
| 56 | +``` |
| 57 | + |
| 58 | +## Documentation |
| 59 | + |
| 60 | +Documentation is mostly done using PHPDoc. I do intend to write actual |
| 61 | +documtation if there is any interest. |
| 62 | + |
| 63 | +## Contributing |
| 64 | + |
| 65 | +I welcome contributions and pull requests. Please note that I do follow |
| 66 | +PSR-2 (and PSR-4 for autoloading). Also, please submit unit tests with |
| 67 | +your work. |
| 68 | + |
| 69 | +GrumPHP enforces at least part of the coding standard, but do make an |
| 70 | +effort to structure your contributions nicely. |
0 commit comments