A quiet peek through the PHP Standard Library (SPL)🤫

Abdulbasit Rubeya
6 min readJan 28, 2024

--

PHP, a versatile and widely used scripting language for server-side development, comes equipped with a rich set of built-in functions and libraries to ease the development process. Among these, the Standard PHP Library (SPL) stands out as a powerful and extensible collection of classes and interfaces that provide a wide range of functionality for common programming tasks. In this piece, we’ll explore several components of the SPL, along with examples to demonstrate their usage

Some of the Concepts, we’ll delve into include

  1. Iterator Interface
  2. ArrayObject Class
  3. SplFileObject Class
  4. SplQueue and SplStack Classes
  5. SplObserver and SplSubject Interfaces

1. Iterator Interface

The iterator interface allows one to traverse through objects as if they were arrays. Classes that implement this interface enable the use of foreach loops on instances of those classes. Let’s consider the following example

$array = [1, 2, 3, 4, 5];
$iterator = new ArrayIterator($array);

foreach ($iterator as $value) {
echo $value . ' ';
}

// Output: 1 2 3 4 5

2. ArrayObject Class

The ArrayObject Class allows objects to work as if they were arrays, It implements various interfaces, including Countable and IteratorAggregate.

Let's try accessing an object without using ArrayObject

<?php

$myObject = (object) ['fruit' => 'apple', 'color' => 'red', 'shape' => 'round'];

echo $myObject['fruit'];

//Fatal error: Cannot use object of type stdClass as array

That one simply failed with a fatal error, now let’s try using the ArrayObject class with the same object and see the output.

<?php

$myObject = (object) ['fruit' => 'apple', 'color' => 'red', 'shape' => 'round'];
$myObject = new ArrayObject($myObject); // using ArrayObject

echo $myObject['fruit'];

// output: apple

You can also add more items to the object in the same way you’d add an item to an array

<?php

$myObject = (object) ['fruit' => 'apple', 'color' => 'red', 'shape' => 'round'];
$myObject = new ArrayObject($myObject);

$myObject['taste'] = 'sweet'; // add new item

echo $myObject['taste'];

// output: sweet

While some developers say that, ArrayObject extends the object to work as an array, I see it more as a conversion (not in a literal sense) of an object to an array, since after using ArrayObject Class on an object, it’s not possible to directly access the properties of the class again the same way you’d access them before using ArrayObject, and Let’s take a look

$myObject = (object) ['fruit' => 'apple', 'color' => 'red', 'shape' => 'round'];
$myObject = new ArrayObject($myObject);

echo $myObject->fruit; // gives a Warning

3. SplFileObject Class

The SplFileObject class offers an object-oriented interface for a file, It extends the SplFileInfo class and implements the SeekableIterator, RecursiveIterator, and RecursiveIteratorIterator interfaces.

Some of the key features included with the class include

  1. Constructor:

$filename (string): The name of the file to open.

2. File Access Methods:

$fileObject->fread($length): Reads up to $length bytes from the file.
$fileObject->fgets(): Reads a line from the file.
$fileObject->fwrite($str): Writes a string to the file.
$fileObject->fseek($offset, $whence = SEEK_SET): Moves the file pointer to a specified position.

3. Iterator Methods:

$fileObject->current(): Gets the current line.
$fileObject->key(): Gets the current line number.
$fileObject->next(): Moves the file pointer to the next line.
$fileObject->rewind(): Rewinds the file pointer to the beginning.
$fileObject->valid(): Checks if the file pointer is at a valid position.

4. File Information:

$fileObject->getFileInfo(): Gets an SplFileInfo object for the file.
$fileObject->getBasename(): Gets the base name of the file.
$fileObject->getExtension(): Gets the file extension.

5. Reading Entire File:

$fileObject->fgetcsv(): Reads a line and parses it as CSV.
$fileObject->file($filename): Reads the entire file into an array.

Let’s take a look at a simple example below

<?php

/*
contents of example.txt:

line 1: Hello world!
line 2: The world is mine!
line 3: How are you today?

*/

$fileObject = new SplFileObject('example.txt', 'r');

// Iterate through lines in the file
foreach ($fileObject as $line) {
echo $line;
}


/*
Output:
Hello world!
The world is mine!
How are you today?
*/

4. SplQueue and SplStack Classes

SPL includes specialized classes for queue and stack implementations. These classes offer methods for enqueueing and dequeueing elements (SplQueue) or pushing and popping elements (SplStack). These classes offer methods to manipulate and iterate through the elements efficiently.

Starting with SplQueue, just envision a literal queue, whether during billing at the supermarket or the bank, whoever comes first shall be serviced first and everyone who comes late stays behind the other person who came earlier and so forth.

// SplQueue example
$queue = new SplQueue();
$queue->enqueue('Mango');
$queue->enqueue('Apple');
$queue->enqueue('Pinaple');

echo $queue->dequeue(); // Output: Mango
echo $queue->dequeue(); // Output: Apple

Meanwhile SplStack, it’s the opposite for SplQueue, metaphorically, this class involves stacking items on top of one another, unlike SplQueue where the first item to come in comes out first, with SplStack whatever came in last comes out first, let’s look at the example below.

// SplStack example
$stack = new SplStack();
$stack->push('came in first');
$stack->push('came in second');
$stack->push('came in last');

echo $stack->pop(); // Output: came in last
echo $stack->pop(); // Output: came in second

In the example above, the SplQueue is used as a queue, and the SplStack is used as a stack. Elements are added to and removed from the data structures, demonstrating their basic operations. Keep in mind that these classes provide more methods than those mentioned here, so you can explore additional functionalities in the official PHP documentation.

5. SplObserver and SplSubject Interfaces

The two classes are used to implement the Observer design pattern, This pattern allows a subject to notify its observers about changes in its state, providing a way to achieve a loosely coupled system where components can react to changes without being directly aware of each other.

The SplObserver interface defines a single method that an observer class must implement

interface SplObserver {
public function update(SplSubject $subject);
}

The update(SplSubject $subject)method is called by the subject whenever its state changes. The observer can then react to the change.

The SplSubject interface on the other hand defines methods that a subject class must implement

interface SplSubject {
public function attach(SplObserver $observer);
public function detach(SplObserver $observer);
public function notify();
}

attach(SplObserver $observer): Adds an observer to the list of observers.
detach(SplObserver $observer): Removes an observer from the list of observers.
notify(): Notifies all observers that the subject's state has changed.

Let’s take a look at a more definitive example of the usage of the SplObserver and SplSubject interfaces

<?php

interface Observer {
public function update(Subject $subject);
}

interface Subject {
public function attach(Observer $observer);
public function detach(Observer $observer);
public function notify();
}

class ConcreteSubject implements Subject {
private $observers = [];
private $state;

public function attach(Observer $observer) {
$this->observers[] = $observer;
}

public function detach(Observer $observer) {
$this->observers = array_filter(
$this->observers,
function ($obs) use ($observer) {
return ($obs !== $observer);
}
);
}

public function notify() {
foreach ($this->observers as $observer) {
$observer->update($this);
}
}

public function setState($state) {
$this->state = $state;
$this->notify();
}

public function getState() {
return $this->state;
}
}

class ConcreteObserver implements Observer {
private $observerState;

public function update(Subject $subject) {
if ($subject instanceof ConcreteSubject) {
$this->observerState = $subject->getState();
echo "Observer updated with state: $this->observerState\n";
}
}
}

// Example usage:
$subject = new ConcreteSubject();
$observer1 = new ConcreteObserver();
$observer2 = new ConcreteObserver();

$subject->attach($observer1);
$subject->attach($observer2);

$subject->setState('Blah Blah Record'); // new state

// output: Observer updated with state: Blah Blah Record

This is just a glimpse into some of the classes, methods, and objects provided by the Standard PHP Library (SPL). While we’ve explored features such as iterators, file handling, data structures, and design patterns, it’s essential to note that SPL encompasses even more functionalities to some of the covered concepts and the uncovered ones in this article like Exception Handling.

This brief overview serves as an invitation to delve deeper into the SPL documentation, where you’ll discover a wealth of features that can significantly enhance your PHP development experience.

Ps. Please reach out if there is something to correct or add to this article.

--

--

Abdulbasit Rubeya
Abdulbasit Rubeya

Responses (2)