Mojo::Util::Collection Documentation

Mojo::Util::Collection

## #Construct

Construct a new collection

                        my $collection = Mojo::Util::Collection->new(
                            items => [
                                { id => 1, first_name => 'John', last_name => 'Doe', age => 20 },
                                { id => 2, first_name => 'Jane', last_name => 'Doe', age => 30 },
                                { id => 3, first_name => 'Jack', last_name => 'Doe', age => 35 },
                                { id => 4, first_name => 'Jill', last_name => 'Doe', age => 40 },
                                { id => 5, first_name => 'James', last_name => 'Doe', age => 45 },
                            ],
                            model => MyApp::Model::User->new,
                        );

## #collect

Instantiate a new collection

                        my $collection = collect({
                            id => 1,
                            first_name => 'John',
                            last_name => 'Doe',
                            age => 20,
                        }, {
                            id => 2,
                            first_name => 'Jane',
                            last_name => 'Doe',
                            age => 30,
                        })->as(sub { MyApp::Model::User->new(@_) });

## #add

Add an item using a hash

                        $collection->add({
                            id => 6,
                            first_name => 'Kate',
                            last_name => 'Doe',
                            age => 30,
                        });

Add an item using a model

                        my $user = MyApp::Model::User->new({
                            id => 6,
                            first_name => 'Kate',
                            last_name => 'Doe',
                            age => 30,
                        });

                        $collection->add($user);

Add an array of items

                        $collection->add([
                            {
                                id => 6,
                                first_name => 'Kate',
                                last_name => 'Doe',
                                age => 30,
                            },
                            {
                                id => 7,
                                first_name => 'Kathy',
                                last_name => 'Doe',
                                age => 35,
                            },
                        ]);

Add an array of models

                        my $user1 = MyApp::Model::User->new({
                            id => 6,
                            first_name => 'Kate',
                            last_name => 'Doe',
                            age => 30,
                        });

                        my $user2 = MyApp::Model::User->new({
                            id => 7,
                            first_name => 'Kathy',
                            last_name => 'Doe',
                            age => 35,
                        });

                        $collection->add([$user1, $user2]);

Add another collection

                        my $collection2 = Mojo::Util::Collection->new(
                            items => [
                                {
                                    id => 6,
                                    first_name => 'Kate',
                                    last_name => 'Doe',
                                    age => 30,
                                },
                                {
                                    id => 7,
                                    first_name => 'Kathy',
                                    last_name => 'Doe',
                                    age => 35,
                                },
                            ],
                            model => MyApp::Model::User->new,
                        );

                        $collection->add($collection2);

## #avg

Return the average of the given $field

                        my $avg = $collection->avg('age'); # 34

## #asOptions

Return an array ref with the following format [{ value => $value, key => $label }]

                        my $options = $collection->asOptions('id', 'full_name');

                        [
                            { value => 1, key => 'John Doe' },
                            { value => 2, key => 'Jane Doe' },
                            { value => 3, key => 'Jack Doe' },
                            { value => 4, key => 'Jill Doe' },
                            { value => 5, key => 'James Doe' },
                        ]

## #count

Return the size of the collection

                        my $count = $collection->count; # 5

## #each

Map through each item and call the callback

                        $collection->each(sub {
                            my $item = shift;

                            # Upper case the first name
                            $item->first_name(uc $item->first_name);
                        });

## #exclude

Exclude objects that doesn't match criteria

                        my $filtered = $collection->exclude(sub {
                            my $item = shift;

                            # Exclude users that are 30 years old
                            return $item->age == 30;
                        });

## #filter

Filter objects by callback

                        my $filtered = $collection->filter(sub {
                            my $item = shift;

                            # Filter users that are 30 years old
                            return $item->age == 30;
                        });

                        bless({
                            'model' => bless({ }, 'MyApp::Model::User'),
                            'objects' => [
                                bless({
                                    'id' => 2,
                                    'first_name' => 'Jane',
                                    'last_name' => 'Doe',
                                    'age' => 30
                                }, 'MyApp::Model::User')
                            ]
                        }, 'Mojo::Util::Collection');

## #find

Find object by primary key, of if args is a hash ref then find first object matching given args

                        my $user = $collection->find(1);

                        bless({ 'id' => 1, 'first_name' => 'John', 'last_name' => 'Doe', 'age' => 20 }, 'MyApp::Model::User');

## #findOrNew

Find object by primary key, or if args is a hash ref then find first object matching given args, or create a new object

                        my $user = $collection->findOrNew({ first_name => 'John', age => 20 });

                        bless({ 'id' => 1, 'first_name' => 'John', 'last_name' => 'Doe', 'age' => 20 }, 'MyApp::Model::User');

## #first

Get first object in collection

                        my $user = $collection->first;

## #firstOrNew

Get first object in collection, or create a new object if collection is empty

                        my $user = $collection->firstOrNew({ first_name => 'Jack', age => 35 }, { id => 3 });

                        bless({ 'id' => 3, 'first_name' => 'Jack', 'last_name' => 'Doe', 'age' => 35 }, 'MyApp::Model::User');

## #get

Get object by index

                        my $item = $collection->get(0);

                        bless({ 'id' => 1, 'first_name' => 'John', 'last_name' => 'Doe', 'age' => 20 }, 'MyApp::Model::User');

## #indexOf

Get the index of the first object that matches the given criteria

                        my $fields = {
                            id => 3,
                            first_name => 'Jack',
                            last_name => 'Doe',
                            age => 35
                        };

                        my $index = $collection->indexOf($fields); # 2

## #last

Get last object in collection

                        my $user = $collection->last;

## #lists

Return an array ref containing all the fields from all objects for the given $field.

                        my $options = $collection->lists('full_name');

                        [ 'John Doe', 'Jane Doe', 'Jack Doe', 'Jill Doe', 'James Doe' ]

Return a hash ref containing $key_field => $value_field if both are given.

                        my $options = $collection->lists('id', 'full_name');

                        {
                            '1' => 'John Doe',
                            '2' => 'Jane Doe',
                            '3' => 'Jack Doe',
                            '4' => 'Jill Doe',
                            '5' => 'James Doe'
                        }

## #max

Return the max value for the given $field

                        my $max = $collection->max('age'); # 45

## #min

Return the min value for the given $field

                        my $min = $collection->min('age'); # 20

## #next

Get the next object in the collection

                        while (my $user = $collection->next) {
                            print $user->full_name . "\n";
                        }

                        John Doe
                        Jane Doe
                        Jack Doe
                        Jill Doe
                        James Doe

## #only

Return an array ref containing only given @fields

                        my $options = $collection->only('full_name', 'age');

                        [
                            { full_name => 'John Doe', age => 20 },
                            { full_name => 'Jane Doe', age => 30 },
                            { full_name => 'Jack Doe', age => 35 },
                            { full_name => 'Jill Doe', age => 40 },
                            { full_name => 'James Doe', age => 45 },
                        ]

## #orderBy

Sort the collection by given $field and $direction

                        my $sorted = $collection->orderBy('full_name', 'desc');

## #page

Return a new collection with the given page number and page size

                        $collection->limit(2);

                        my $page = $collection->page(2);

                        bless({
                            'model' => bless({ }, 'MyApp::Model::User'),
                            'objects' => [
                                bless({
                                    'id' => 3,
                                    'first_name' => 'Jack',
                                    'last_name' => 'Doe',
                                    'age' => 35
                                }, 'MyApp::Model::User'),
                                bless({
                                    'id' => 4,
                                    'first_name' => 'Jill',
                                    'last_name' => 'Doe',
                                    'age' => 40
                                }, 'MyApp::Model::User')
                            ]
                        }, 'Mojo::Util::Collection');

## #remove

Remove an item from the collection by index or by object

                        my $user = MyApp::Model::User->new({
                            id => 3,
                            first_name => 'Jane',
                            last_name => 'Doe',
                            age => 30,
                        });

                        $collection->remove($user);

## #search

Search for objects that match the given criteria

                        my $users = $collection->search({ first_name => 'Jane' });

                        bless({
                            'model' => bless({ }, 'MyApp::Model::User'),
                            'objects' => [
                                bless({
                                    'id' => 3,
                                    'first_name' => 'Jane',
                                    'last_name' => 'Doe'
                                }, 'MyApp::Model::User')
                            ]
                        }, 'Mojo::Util::Collection');

## #slice

Return a new collection with elements starting at $start and ending at $end

                        my $users = $collection->slice(1, 3);

## #sum

Return the sum of the given $field

                        my $sum = $collection->sum('age'); # 170

## #toArray

Serialize all the objects

                        my $array = $collection->toArray;

                        [
                            { id => 1, first_name => 'John', last_name => 'Doe', age => 20 },
                            { id => 2, first_name => 'Jane', last_name => 'Doe', age => 30 },
                            { id => 3, first_name => 'Jack', last_name => 'Doe', age => 35 },
                            { id => 4, first_name => 'Jill', last_name => 'Doe', age => 40 },
                            { id => 5, first_name => 'James', last_name => 'Doe', age => 45 },
                        ]

## #toCsv

Serialize all the objects to CSV

                        my $csv = $collection->toCsv('Id,Full Name,Age', qw/id,full_name,age/);

                        Id,Full Name,Age
                        1,John Doe,20
                        2,Jane Doe,30
                        3,Jack Doe,35
                        4,Jill Doe,40
                        5,James Doe,45

## #toJson

Serialize all the objects to JSON

                        my $json = $collection->toJson;

## #touch

Update the age field for all objects in the collection

                        $collection->touch(sub {
                            my $item = shift;

                            $item->age($item->age + 1);
                        });

## #unique

Return an array ref containing only unique values for given $field

                        my $unique = $collection->unique('first_name');

                        ['John', 'Jane', 'Jack', 'Jill', 'James']

## #whereIn

Return a new collection with objects that match the given criteria

                        my $filtered = $collection->whereIn('first_name', ['John', 'Jane']);

## #whereNotIn

Return a new collection with objects that don't match the given criteria

                        my $filtered = $collection->whereNotIn('first_name', ['John', 'Jane']);

## #MyApp::Model::User

MyApp::Model::User

                        package MyApp::Model::User;
                        use Mojo::Base 'Mojo::Util::Model';

                        # Attributes
                        has 'full_name' => sub {
                            my $self = shift;

                            return $self->first_name . ' ' . $self->last_name;
                        };

                        1;