All Projects → loophp → Collection

loophp / Collection

Licence: mit
A (memory) friendly, easy, lazy and modular collection class.

Projects that are alternatives of or similar to Collection

Imlazy
😴 Functional programming with lazy immutable iterables
Stars: ✭ 89 (-73.11%)
Mutual labels:  immutable, iterator, generator
Box Shadows.css
♓️ A cross-browser collection of CSS box-shadows
Stars: ✭ 335 (+1.21%)
Mutual labels:  collection, generator
iteration utilities
Utilities based on Pythons iterators and generators.
Stars: ✭ 65 (-80.36%)
Mutual labels:  generator, iterator
Tstl
TypeScript-STL (Standard Template Library, migrated from C++)
Stars: ✭ 397 (+19.94%)
Mutual labels:  iterator, collection
rrbit
An Immutable vectors/lists/arrays library using the Relaxed Radix Balancing(RRB) technique
Stars: ✭ 12 (-96.37%)
Mutual labels:  immutable, collection
Immutagen
A library for simulating immutable generators in JavaScript
Stars: ✭ 115 (-65.26%)
Mutual labels:  immutable, generator
Rubico
[a]synchronous functional programming
Stars: ✭ 133 (-59.82%)
Mutual labels:  iterator, generator
php-sorted-collections
Sorted Collections for PHP
Stars: ✭ 22 (-93.35%)
Mutual labels:  collection, iterator
Laravel Api To Postman
Generate a Postman collection automatically from your Laravel API
Stars: ✭ 320 (-3.32%)
Mutual labels:  collection, generator
Mktorrent
A simple command line utility to create BitTorrent metainfo files
Stars: ✭ 302 (-8.76%)
Mutual labels:  generator
Google Hosts
Google hosts generator
Stars: ✭ 3,277 (+890.03%)
Mutual labels:  generator
Motionia
Motionia is a lightweight simplified on demand animation library!
Stars: ✭ 294 (-11.18%)
Mutual labels:  generator
Medical Datasets
tracking medical datasets, with a focus on medical imaging
Stars: ✭ 296 (-10.57%)
Mutual labels:  collection
React Antd
基于react + redux + immutable + less + ES6/7 + webpack2.0 + fetch + react-router + antd实现的SPA后台管理系统模板
Stars: ✭ 321 (-3.02%)
Mutual labels:  immutable
Php Initial Avatar Generator
Generate avatars with initials from user names.
Stars: ✭ 302 (-8.76%)
Mutual labels:  generator
Graphback
Graphback - Out of the box GraphQL server and client
Stars: ✭ 323 (-2.42%)
Mutual labels:  generator
Sequency
⚡️ Type-safe functional sequences for processing iterable data
Stars: ✭ 294 (-11.18%)
Mutual labels:  collection
Awesome Micropython
A curated list of awesome MicroPython libraries, frameworks, software and resources.
Stars: ✭ 287 (-13.29%)
Mutual labels:  collection
Sample Programs
Sample Programs in Every Programming Language
Stars: ✭ 323 (-2.42%)
Mutual labels:  collection
Awesome Ruby China
A collection of excellent topics. https://ruby-china.org/topics/excellent
Stars: ✭ 323 (-2.42%)
Mutual labels:  collection

Latest Stable Version GitHub stars Total Downloads GitHub Workflow Status Scrutinizer code quality Type Coverage Code Coverage License Donate! Donate!

PHP Collection

Description

Collection is a functional utility library for PHP greater than 7.4.

It's similar to other collection libraries based on regular PHP arrays, but with a lazy mechanism under the hood that strives to do as little work as possible while being as flexible as possible.

Functions like array_map(), array_filter() and array_reduce() are great, but they create new arrays and everything is eagerly done before going to the next step. Lazy collection leverages PHP's generators, iterators and yield statements to allow you to work with very large data sets while keeping memory usage as low as possible.

For example, imagine your application needs to process a multi-gigabyte log file while taking advantage of this library's methods to parse the file. Instead of reading and storing the entire file into memory at once, this library may be used to keep only a small part of the file in memory at a given time.

On top of this, this library:

Except a few methods, most methods are pure and return a new Collection object.

Also, unlike regular PHP arrays where keys must be either of type int or string, this collection library let you use any kind of type for keys: integer, string, objects, arrays, ... anything! This library could be a valid replacement for \SplObjectStorage but with much more features. This way of working opens up new perspectives and another way of handling data, in a more functional way.

And last but not least, collection keys are preserved throughout most operations, and it might be leading to some confusions, carefully read this example for the full explanation.

This library has been inspired by:

Features

  • Decoupled: Each Collection methods is a shortcut to one isolated standard class, each operation has its own responsibility. Usually the arguments needed are standard PHP variables like int, string, callable or iterator. It allows users to use those operations individually, at their own will to build up something custom. Currently, more than 80 operations are available in this library. This library is basically an example of what you can do with all those small bricks, but nothing prevent users to use an operation on its own as well.

  • It takes function first, data-last: In the following example, multiple operations are created. The data to be operated on is generally supplied at last.

    <?php
    
    $data = ['foo', 'bar', 'baz'];
    $filterCallback = static fn(string $userId): bool => 'foo' !== $userId;
    
    // Using the Collection library
    $collection = Collection::fromIterable($data)
        ->filter($filterCallback)
        ->reverse();
    print_r($collection->all()); // ['baz', 'bar']
    
    // Using single operations.
    $filter = Filter::of()($filterCallback);
    $reverse = Reverse::of();
    $pipe = Pipe::of()($reverse, $filter);
    
    print_r(iterator_to_array($pipe(new ArrayIterator($data))));  // ['baz', 'bar']
    

    More information about this in the Brian Lonsdorf's conference, even if this is for Javascript, those concepts are common to other programming languages.

    In a nutshell, the combination of currying and function-first enables the developer to compose functions with very little code (often in a “point-free” fashion), before finally passing in the relevant user data.

  • Operations are stateless and curried by default: This currying makes it easy to compose functions to create new functions. Because the API is function-first, data-last, you can continue composing and composing until you build up the function you need before dropping in the data. See this Hugh Jackson article describing the advantages of this style.

    In the following example, the well-known flatMap could be composed of other operations as such:

    <?php
    
    $input = ['foo,bar', 'baz,john'];
    $userData = new ArrayIterator($input);
    
    $flatMap = static fn (callable $callable) =>
                   Pipe::of()(
                      Map::of()($callable),
                      Flatten::of()(1),
                      Normalize::of()
                   );
    
    $callback = fn(string $name): array => explode(',', $name);
    
    print_r(iterator_to_array($flatMap($callback)($userData))); // ['foo', 'bar', 'baz', 'john']
    

Installation

composer require loophp/collection

Usage

Check out the usage page, it contains trivial and more advanced use cases.

Documentation

On top of a complete documented code, the package include a full documentation that gets automatically compiled and published upon each commit at https://loophp-collection.rtfd.io.

The API will give you a pretty good idea of the existing methods and what you can do with it.

I'm doing my best to keep the documentation up to date, if you found something odd, please let me know in the issue queue.

Code quality, tests and benchmarks

Every time changes are introduced into the library, Github run the tests.

The library has tests written with PHPSpec. Feel free to check them out in the spec directory. Run composer phpspec to trigger the tests.

Before each commit some inspections are executed with GrumPHP, run composer grumphp to check manually.

The quality of the tests is tested with Infection a PHP Mutation testing framework, run composer infection to try it.

Static analysers are also controlling the code. PHPStan and PSalm are enabled to their maximum level.

PHP Insights is also launched in Github actions just for information. (example of PHP Insights report, you must be logged on Github to see it)

Contributing

Feel free to contribute by sending Github pull requests. I'm quite reactive :-)

If you can't contribute to the code, you can also sponsor me on Github or Paypal.

On the internet

Changelog

See CHANGELOG.md for a changelog based on git commits.

For more detailed changelogs, please check the release changelogs.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].