framework icon indicating copy to clipboard operation
framework copied to clipboard

[Proposal] Collection helper function - code included.

Open DanSmith70 opened this issue 13 years ago • 8 comments

I've been using the Collection class a fair bit in my code, so I decided to make a little helper for it. Is there any interest for this in the core?

if ( ! function_exists('collection'))
{
    function collection($items = array())
    {
        return new Illuminate\Support\Collection($items);
    }
}

You can then get an new empty collection with $collection = collection(); or of course pass in an array of items to pre-fill the collection: $collection = collection(['one','two','three']);

DanSmith70 avatar Jun 20 '13 10:06 DanSmith70

Isn't

$collection = new Illuminate\Support\Collection(['one','two','three']);

semantically better, rather than creating a wrapper for this?

bastuijnman avatar Jun 20 '13 13:06 bastuijnman

@bastuijnman Sure but then why use Facades or helper functions at all? The main point of Laravel is reduce code verbosity and make it more expressive. Perhaps the function could be new_collection() or array_object()?

DanSmith70 avatar Jun 20 '13 13:06 DanSmith70

Think it comes down to a matter of taste, I usually do:

use Illuminate\Support\Collection as Collection;

I can then just do

$collection = new Collection($items);

Which I find to be as expressive (if not more, as you can see immidiatly that you're instantiating a Class) as using a helper function

bastuijnman avatar Jun 20 '13 13:06 bastuijnman

True and I used to do it that way as well, and of course there is nothing stopping anyone using that method even with the helper included, if they prefer it :)

DanSmith70 avatar Jun 20 '13 14:06 DanSmith70

True indeed :)

bastuijnman avatar Jun 20 '13 14:06 bastuijnman

Or to continue on what @bastuijnman add 'Collection' => 'Illuminate\Support\Collection' in your aliases ands then you can pretty much do new Collection($items) everywhere, which is almost as short as collection($items).

Anahkiasen avatar Jun 21 '13 17:06 Anahkiasen

I am wit @Anahkiasen and @bastuijnman. The helpers are typically for primitive, low-level data. When dealing with classes, use classes.

bencorlett avatar Jun 24 '13 01:06 bencorlett

Can define in your own apps.

taylorotwell avatar Jul 29 '13 19:07 taylorotwell