"Higher-order messages" for Laravel Collections

in utopian-io •  7 years ago  (edited)

Pull request: https://github.com/laravel/framework/pull/16267

Inspired by an article that described how to implement this feature in Ruby, I decided to propose "higher-order messages" for inclusion in Laravel's popular Collection class.

This feature allows a more terse syntax for collection pipeline operations. Let's take a look at an example:

// "Normal" syntax
$employees->reject(function($employee) {
    return $employee->retired; 
})->each(function($employee){
    $employee->sendPayment();
});

// New syntax
$employees
    ->reject->retired
    ->each->sendPayment();

While many hate the unfamiliar and non-obvious syntax, it is also likened by many as a way to avoid the rather clumsy PHP syntax for anonymous functions (especially for short ones).

I am still not 100% convinced whether this was a good idea or not. Seeing code such as this when you don't know what's going on behind the scenes can be intimidating and it's certainly not self-explanatory. Still, it's probably one of the most popular features I have ever contributed to Laravel (at the very least, it is the most controversial).

Implementation

When accessing one of the supported methods (such as map() and filter()) as a property rather than a method, Collection returns a proxy object that then passes on any property access or method call - wrapped in a closure - to the original method on the Collection class (hence the "higher-order message" name).



Posted on Utopian.io - Rewarding Open Source Contributors

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

The Pull Request must have been merged within the past 14 days.

As in your case the Pull Request was merged on "Nov 4, 2016"

You can contact us on Discord.
[utopian-moderator]

Congratulations @franzliedke! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

Are you a DrugWars early adopter? Benvenuto in famiglia!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!