This post is from a low-reputation account and contains an unverified outbound link. Be cautious before clicking external links.

"Higher-order messages" for Laravel Collections

Words
197
Reading
1 min
Listen
Play
9y

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

"Higher-order messages" for Laravel Collections | Ecency