PHP Class that allows advanced operations on arrays of objects
For the following examples, we'll assume a set of objects that look something like table rows from a database:
$objects = [
(object)[
'id' => 0,
'name' => 'Widget',
'colour' => 'red',
'quantity' => 5
],
(object)[
'id' => 1,
'name' => 'Gadget',
'colour' => 'red',
'quantity' => 2
],
(object)[
'id' => 2,
'name' => 'Spudger',
'colour' => 'green',
'quantity' => 10
],
(object)[
'id' => 3,
'name' => 'Gizmo',
'colour' => 'green',
'quantity' => 4
]
];
$smartSet = new \D2K\SmartSet($objects);
$firstObject = $smartSet('id', 0);
// $firstObject == (object)['id' => 0, ...]
$redObjects = $smartSet('colour', 'red');
// $redObjects == \D2K\SmartSet([
// (object)['id' => 0, ...],
// (object)['id' => 1, ...] ])
$byID = $smartSet->index('id');
// $byID == [
// 0 => (object)['id' => 0, ...],
// 1 => (object)['id' => 1, ...],
// ...]
$byColour = $smartSet->index('colour', true);
// $byColour == [
// 'red' => [
// (object)['id' => 0, ...],
// (object)['id' => 1, ...] ],
// 'green' => [
// (object)['id' => 2, ...],
// (object)['id' => 3, ...] ]
// ]
$names = $smartSet->property('name');
// $names == ['Widget', 'Gadget', 'Spudger', 'Gizmo']
function byQuantity($a, $b)
{
return $a->quantity <=> $b->quantity;
}
$smartSet->sort('byQuantity');
function addOne($index, $item)
{
$item->quantity++;
}
$smartSet->map('addOne');
function describe($index, $item)
{
return $item->colour . ' ' . $item->name;
}
$descriptions = $smartSet->each('describe');
// $descriptions == ['red Widget', 'red Gadget', 'green Spudger', 'green Gizmo']
Let's imagine each object has the following public method:
function inStock($minimumStock = 0)
{
return $this->quantity > $minimumStock;
}
Then we can call this method across the set, with a minimumStock of 3 like so:
$hasStock = $smartSet->callMethod('inStock', [3]);
// $hasStock == [ true, false, true, true ]
SmartSet implements Iterator and Countable, so you can use it like a normal array as well:
$redGadget = $smartSet[1];