DEV Community

Martin Jirasek
Martin Jirasek

Posted on

A Simple Trick to Organize Your PHP Collections Effectively

This is our Bag class — and yes, we absolutely love its simplicity 🥰

class Bag
{
    public function __construct(public array $items = []) {}
}
Enter fullscreen mode Exit fullscreen mode

HOW TO WORK WITH IT?

The long way (a.k.a. “why make it simple?”)

  1. Create collection objects
  2. Insert them into another collection
  3. Fill them with items
$bagA = new Bag();
$bagB = new Bag();

$preparedObjects = [];
$preparedObjects[] = $bagA;
$preparedObjects[] = $bagB;

$bagA->items[] = 'Bag A item 1';
$bagA->items[] = 'Bag A item 2';

$bagB->items[] = 'Bag B item 1';
$bagB->items[] = 'Bag B item 2';
Enter fullscreen mode Exit fullscreen mode

The simpler way (clean, elegant, instant 😌)

  1. Create and insert objects right away
  2. Then just fill them
$preparedObjects = [
    $bagA = new Bag(),
    $bagB = new Bag(),
];

$bagA->items[] = 'Bag A item 1';
$bagA->items[] = 'Bag A item 2';

$bagB->items[] = 'Bag B item 1';
$bagB->items[] = 'Bag B item 2';
Enter fullscreen mode Exit fullscreen mode

Top comments (0)