PHP code example of mcaskill / charcoal-model-collection

1. Go to this page and download the library: Download mcaskill/charcoal-model-collection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mcaskill / charcoal-model-collection example snippets


$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [
//     1 => Model (active: 1), 2 => Model (active: 0),
//     3 => Model (active: 1), 4 => Model (active: 1),
//     5 => Model (active: 0)
// ]

$filtered = $collection->filter(function ($obj, $id) {
    return ($obj['active'] === true);
});
// [ 1 => Model, 3 => Model, 4 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e, $f, $g, $h, $i, $j ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model,… ]

$chunk = $collection->forPage(2, 3);
// [ 4 => Model, 5 => Model, 6 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model ]

$filtered = $collection->only(2);
// [ 2 => Model ]

$filtered = $collection->only([ 1, 3 ]);
// [ 1 => Model, 3 => Model ]

$filtered = $collection->only(2, 4);
// [ 2 => Model, 4 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model ]

$collection->pop();
// Model (5)

$collection->toArray();
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model ]

$collection->prepend($o);
// Model (15)

$filtered->toArray();
// [ 15 => Model, 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model ]

$collection->random();
// Model (3)

$collection->random(2);
// [ 1 => Model, 3 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model ]

$reversed = $collection->reverse();
// [ 5 => Model, 4 => Model, 3 => Model, 2 => Model, 1 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model ]

$collection->shift();
// Model (1)

$collection->toArray();
// [ 2 => Model, 3 => Model, 4 => Model, 5 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e, $f, $g, $h, $i, $j ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model,… ]

$slice = $collection->slice(4);
// [ 5 => Model, 6 => Model, 7 => Model, 8 => Model, 9 => Model, 10 => Model ]

$slice = $collection->slice(4, 2);
// [ 5 => Model, 6 => Model ]

$collection = new Collection([ $a, $b, $c ]);
// [ 1 => Model (position: 5), 2 => Model (position: 2), 3 => Model (position: 0) ]

$sorted = $collection->sortBy('position');
// [ 3 => Model, 2 => Model, 1 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e, $f ]);
// [ 1 => Model, 2 => Model, 3 => Model, 4 => Model, 5 => Model, 6 => Model ]

$chunk = $collection->take(3);
// [ 1 => Model, 2 => Model, 3 => Model ]

$chunk = $collection->take(-2);
// [ 5 => Model, 6 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [
//     1 => Model (active: 1), 2 => Model (active: 0),
//     3 => Model (active: 1), 4 => Model (active: 1),
//     5 => Model (active: 0)
// ]

$filtered = $collection->where('active', true);
// [ 1 => Model, 3 => Model, 4 => Model ]

$collection = new Collection([ $a, $b, $c, $d, $e ]);
// [
//     1 => Model (name: "Lorem"), 2 => Model (name: "Ipsum"),
//     3 => Model (name: "Dolor"), 4 => Model (name: "Elit"),
//     5 => Model (name: "Amet")
// ]

$filtered = $collection->whereIn('name', [ 'Amet', 'Dolor' ]);
// [ 3 => Model, 5 => Model ]

$repository = (new CollectionLoaderIterator)->setModel(Post::class);

$repository->addFilter('active', true)->addFilter('published <= NOW()');

$posts = $repository->load();
// query: SELECT …
// array: Post, Post, Post,…

foreach ($posts as $post) {
    echo $post['title'];
}

$repository = (new CollectionLoaderIterator)->setModel(Post::class);

$repository->addFilter('active', true)->addFilter('published <= NOW()');

$posts = $repository->cursor();
// Generator

foreach ($posts as $post) { // query: SELECT …
    // Post
    echo $post['title'];
}

class Post extends AbstractModel
{
    /**
     * @return Comment[]|CollectionLoaderIterator
     */
    public function getComments() : iterable
    {
        $comments = (new CollectionLoaderIterator)->setModel(Comment::class);

        $byPost = [
            'property' => 'post_id',
            'value'    => $this['id'],
        ];

        return $comments->addFilter($byPost);
    }
}

$post = $factory->create(Post::class)->load(1);

foreach ($post['comments'] as $comment) { // query: SELECT …
    // Comment
}

$post = $factory->create(Post::class)->load(1);

$comments = $post['comments']->addFilter('approved', true);
// CollectionLoaderIterator

foreach ($comments as $comment) { // query: SELECT …
    // Comment
}

$repository = (new CollectionLoaderIterator)->setModel(Post::class);

$repository->addFilter('active', true)
           ->addFilter('published <= NOW()')
           ->setNumPerPage(10)
           ->setPage(3);

// Automatically find total count from query builder
$posts = $repository->load();
// query: SELECT SQL_CALC_FOUND_ROWS * FROM `charcoal_users` WHERE ((`active` = '1') AND (`published` <= NOW())) LIMIT 30, 10;
// query: SELECT FOUND_ROWS();
$total = $repository->foundObjs();
// int: 38

// Automatically find total count from query
$users = $repository->reset()->loadFromQuery('SELECT SQL_CALC_FOUND_ROWS * … LIMIT 0, 20');
// query: SELECT SQL_CALC_FOUND_ROWS * … LIMIT 0, 20;
// query: SELECT FOUND_ROWS();
$total = $repository->foundObjs();
// int: 38

// Automatically find total count from query
$users = $repository->reset()->loadFromQuery('SELECT * … LIMIT 0, 20');
// query: SELECT * … LIMIT 0, 20;
$total = $repository->foundObjs();
// LogicException: Can not count found objects for the last query

$repository = (new ModelCollectionLoader)->setModel(Post::class);

// …

$repository->setModel(Comment::class);
// RuntimeException: A model is already assigned to this collection loader: \App\Model\Post

$postsLoader    = (new ModelCollectionLoader)->setModel(Post::class);
$commentsLoader = (clone $postsLoader)->setModel(Comment::class);

$postsLoader    = (new ModelCollectionLoader)->setModel(Post::class);
$commentsLoader = $postsLoader->cloneWith(Comment::class);
$tagsLoader     = $postsLoader->cloneWith([
    'model'      => Tag::class,
    'collection' => 'array',
]);

$posts = (new BaseCollectionLoader)->setModel(Post::class)->load();
// array: Post, Post, Post,…

($posts[0]->source() === $posts[2]->source())
// bool: false

$posts = (new ModelCollectionLoader)->setModel(Post::class)->load();
// array: Post, Post, Post,…

($posts[0]->source() === $posts[2]->source())
// bool: true

$repository = new ScopedCollectionLoader([
    'logger'          => $container['logger'],
    'factory'         => $container['model/factory'],
    'model'           => Post::class,
    'default_filters' => [
        [
            'property' => 'active',
            'value'    => true,
        ],
        [
            'property' => 'publish_date',
            'operator' => 'IS NOT NULL',
        ],
    ],
    'default_orders'  => [
        [
            'property'  => 'publish_date',
            'direction' => 'desc',
        ],
    ],
    'default_pagination' => [
        'num_per_page' => 20,
    ],
]);

$posts = $repository->addFilter('publish_date <= NOW()')->load();
// query: SELECT SQL_CALC_FOUND_ROWS * FROM `posts` WHERE ((`active` = '1') AND (`publish_date` IS NOT NULL) AND (`published` <= NOW())) ORDER BY `publish_date` DESC LIMIT 20;

$repository->reset()->load();
// query: SELECT SQL_CALC_FOUND_ROWS * FROM `posts` WHERE ((`active` = '1') AND (`publish_date` IS NOT NULL)) ORDER BY `publish_date` DESC LIMIT 20;

$repository = new ScopedCollectionLoader([…]);

$posts = $repository->withoutDefaults(function () {
    $this->applyDefaultOrders();
    $this->applyDefaultPagination();
})->load();
// query: SELECT SQL_CALC_FOUND_ROWS * FROM `posts` ORDER BY `publish_date` DESC LIMIT 20;

$repository = new CachedCollectionLoader([
    'cache'   => $container['cache'],
    'logger'  => $container['logger'],
    'factory' => $container['model/factory'],
    'model'   => Post::class,
]);

$repository = new CachedCollectionLoader([…]);

$posts = $repository->withoutCache()->cursor();
// Generator