Lab 06: SPL Advanced

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm php:8.3-cli bash

Overview

PHP's Standard PHP Library (SPL) provides efficient data structures far beyond simple arrays. This lab benchmarks SplFixedArray, explores heaps, priority queues, linked lists, and builds custom iterators for production use cases.


Step 1: SplFixedArray vs PHP Array — Memory Benchmark

<?php
$size = 100_000;

// SplFixedArray: fixed-size, integer-indexed, ~30% less memory
$mem1 = memory_get_usage(true);
$fixed = new SplFixedArray($size);
for ($i = 0; $i < $size; $i++) {
    $fixed[$i] = $i;
}
$mem2 = memory_get_usage(true);

// PHP array: flexible, hash-based, more overhead
$mem3 = memory_get_usage(true);
$arr = range(0, $size - 1);
$mem4 = memory_get_usage(true);

echo "=== Memory Comparison ({$size} integers) ===\n";
echo "SplFixedArray: " . round(($mem2 - $mem1) / 1024, 1) . " KB\n";
echo "PHP array:     " . round(($mem4 - $mem3) / 1024, 1) . " KB\n";
echo "Saving:        " . round((1 - ($mem2-$mem1)/($mem4-$mem3)) * 100, 1) . "%\n";

// Conversion
$backToArray = $fixed->toArray();
echo "\nConversion: SplFixedArray → array, first 5: " . implode(', ', array_slice($backToArray, 0, 5)) . "\n";

// From array
$fixed2 = SplFixedArray::fromArray([10, 20, 30, 40, 50], preserveKeys: false);
echo "fromArray: " . implode(', ', $fixed2->toArray()) . "\n";
echo "Size: " . $fixed2->getSize() . "\n";

📸 Verified Output:


Step 2: SplMinHeap & SplMaxHeap

📸 Verified Output:


Step 3: SplPriorityQueue

📸 Verified Output:


Step 4: SplDoublyLinkedList, SplStack, SplQueue


Step 5: ArrayObject with ARRAY_AS_PROPS


Step 6: RecursiveIteratorIterator


Step 7: Custom Iterator & IteratorAggregate

📸 Verified Output:


Step 8: Capstone — High-Performance Data Pipeline

📸 Verified Output:


Summary

Structure
Class
Complexity
Best For

Fixed array

SplFixedArray

O(1) access

Memory-efficient numeric arrays

Min-heap

SplMinHeap

O(log n) insert/extract

Priority queues, Dijkstra

Max-heap

SplMaxHeap

O(log n) insert/extract

Top-N problems

Priority queue

SplPriorityQueue

O(log n)

Job scheduling

Linked list

SplDoublyLinkedList

O(1) push/pop

Deque operations

Stack

SplStack

O(1) push/pop

Undo/redo, recursion simulation

Queue

SplQueue

O(1) enqueue/dequeue

BFS, work queues

Array object

ArrayObject

O(1)

Typed collections with OOP

Recursive iterator

RecursiveIteratorIterator

O(n)

Tree traversal

Custom iterator

Iterator interface

User-defined

Lazy evaluation, pagination

Last updated