Skip to content

dsheiko/extras

Repository files navigation

Dsheiko\Extras

Dsheiko\Extras

Latest Stable Version Total Downloads License

JavaScript-style utility methods for PHP. Chainable map, filter, reduce, and dozens more — consistent naming, predictable argument order, and a familiar API inspired by Underscore.js and Lodash.

The name comes from "Array Extras" — the array methods added in ES5 that made JavaScript array manipulation practical.

Installation

composer require "dsheiko/extras"

Highlights

  • Consistent naming — all methods use camelCase instead of PHP's mixed lower_case conventions
  • Consistent argument order — target value always comes first: Arrays::method($target, ...$options)
  • Chainable interfaceAny::chain($value)->map(...)->filter(...)->value()
  • PlainObject — a JavaScript-style plain object with dot-access and chainable methods
  • Native performance — built on PHP's own functions; no foreach where a built-in can do the job
  • Familiar API — methods match JavaScript, Underscore.js, and Lodash where possible

Utility Sets

Set Types covered
Arrays PHP arrays
Collections Iterable, ArrayObject, Iterator
Strings PHP strings
Numbers Integer, Double, NaN
Booleans PHP booleans
Functions PHP callables
Plain Object stdClass-like objects
Any Any PHP type
Chaining Fluent chain API
Utilities Standalone helpers

Download

Dsheiko\Extras Cheatsheet (PDF)

Architecture

Overview

Examples

Static method call

<?php
use \Dsheiko\Extras\Arrays;

function numToArray(int $num): array
{
    return [$num];
}

$res = Arrays::map(range(1, 3), "numToArray"); // [[1],[2],[3]]

Chaining

<?php
use \Dsheiko\Extras\Any;

$res = Any::chain(new \ArrayObject([1, 2, 3]))
    ->toArray()                                    // [1,2,3]
    ->map(function($num) { return ["num" => $num]; })
    ->reduce(function($carry, $arr) {
        $carry .= $arr["num"];
        return $carry;
    }, "")                                         // "123"
    ->replace("/2/", "")                           // "13"
    ->then(function($value) {
        if (empty($value)) {
            throw new \Exception("Empty value");
        }
        return $value;
    })
    ->value();

echo $res; // "13"

Constructing from an object

<?php
use \Dsheiko\Extras\Arrays;

class Foo
{
    public $bar = "BAR";
}

$arr = Arrays::from(new Foo); // ["bar" => "BAR"]

PlainObject

<?php
use \Dsheiko\Extras\Arrays;

$po = Arrays::object(["foo" => "FOO", "bar" => ["baz" => "BAZ"]]);
echo $po->foo;              // FOO
echo $po->bar->baz;         // BAZ
var_dump($po->bar->entries()); // [["baz", "BAZ"]]

Packages

 
 
 

Contributors