Have you ever found yourself in the situation when you need to evaluate and transform some data which is in a list, basically filter-map-reducing it? It's an everyday job! Somehow PHP doesn't have prebuilt Array API like does Javascript or Java, which is a very convenient way to chain your operations, and by the way it should be lazy - which means not traversing your data in every chained function. Instead it would stack your calls and then dump it to terminal operation when it is time.
I mean something like this, and imagine there are millions of traversables there (written in pseudo-js-code):
dataArray // a lot of records from database
.filter((e) => !!e.subData) // must have "subData"
.map((e) => e.subData) // extract "subData"
.filter((sd) => !!sd.user) // must have "user"
.map((sd) => sd.user) // extract "user"
.foreach((user) => log('user: ', user)) // collect extracted users
.map((user) => {
return {...user, total: user.money * user.days};
}) // add some 'total' to each user
.groupBy((user) => round(user.total / 1000)) // somehow group users
.mapAll((user) => user.total) // transform all groups
.reduceAll((sum, total) => sum + total) // sum values in groups
.collect(); // and finally get the result
Nice and clear!
However in PHP it is impossible unless you dig the web to find something suitable.
Welcome PHP Stream API - heavily inspired by Java Stream API and enriched by Underscore methods - convenient array mutation and filtering conveyor, that takes the pain of working with traversables in PHP.
Fork, test, comment, like, subscribe, ring the bell (joke) :)
It is not final, but together we can make it the best!
I'll be adding some reasonable stuff while using it in my everyday job if something comes up my mind.
K! THX! BYE!
Top comments (0)