PHP data structures: spl Stack

Why no array?

Sometimes (yes in web development too) you need to optimize your code for speed and memory usage. PHP is simplified by design and heavily depends on array usage. You can speed things up a little using proper data structures for the job. Luckily the language provides build in classes and interfaces for the most frequent data structures, all wrapped in SPL library. Implementing Stack makes your code cleaner and more readable. We are going to utilize SplStack abstract class, and build Stack to address very common problem in every day programming which is clean dishes pile.

<?php

class PlateCupboard extends SplStack
{
    public function addCleanPlate($plate)
    {
        // Push clean plate on top of the stack.
        return parent::push($plate);
    }
    public function takeCleanPlate()
    {
        try {
            // Take first, top item from the stack.
            return parent::pop();
        } catch (RuntimeException $ex) {
            // expect SplStack exception if there are no more plates in the cupboard.
            echo 'There are no more plates in cupboard';
        }
    }
}

$cupboard = new PlateCupboard();

// Add 3 different color plates.
$cupboard->addCleanPlate('Yellow');
$cupboard->addCleanPlate('Red');
$cupboard->addCleanPlate('Black');

// Take topmost clean plate.
var_dump($cupboard->takeCleanPlate());
// Outputs: Black

// You can access SplStack inherited methods directly from now on.
var_dump($cupboard->count());
// Outputs: 2

// Check if you like the color of first plate, but don't take it.
var_dump($cupboard->top());
// Outputs: Red

// You can iterate through cupboard items like an array.
foreach ($cupboard as $plate) {
    echo $plate . PHP_EOL;
}
/* Stack is LIFO datastruckture so last inserted item is going to be first array item.
 * Outputs:
 *  Red
 *  Yellow
 */

Summary:

Using Stack in PHP is very easy. Your class need to extend SplStack abstract class, and you are good to go. Overriding or building custom methods like in the example above is only needed if there is additional functionality required.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *