Null Object Design Pattern in PHP

Null object design pattern is a software design pattern where the null object replaces the checking for null values. It defines the default behavior of some service class method and does nothing.

Null Object Design Pattern UML Diagram

PHP Example of Null Object Pattern

Below is a simple example of different types of commands and application which uses them.

<?php

interface CommandInterface
{
    public function execute();
}

class OutputCommand implements CommandInterface
{
    public function execute()
    {
        echo 'Output from the command';
    }
}

class FileCommand implements CommandInterface
{
    public function execute()
    {
        file_put_contents(__DIR__.'/log.txt', date('Y-m-d H:i:s'), FILE_APPEND | LOCK_EX);
    }
}

class NullCommand implements CommandInterface
{
    public function execute()
    {
        // Do nothing.
    }
}

class Application
{
    public function run(CommandInterface $command = null)
    {
        $executableCommand = $command ?? new NullCommand();

        return $executableCommand->execute();
    }
}

Usage is then the following:

<?php
// ...

$outputCommand = new OutputCommand();
$fileCommand = new FileCommand();
$app = new Application();

// Echo predefined string
$application->run($outputCommand); // Output from the command

// Create a file and append string to it
$application->run($fileCommand);

// Do nothing
$application->run();

If we run the application without providing it the command it does nothing because in that case it uses the null object NullCommand. Without the null object we would have to check that in the client code which becomes messy as more commands are added or in more complex situations.

Open Source PHP Implementations

Some examples of the null object design pattern implementations in open source:

See Also

GitHub OctocatFound a typo? Something wrong with this content? Just fork and edit it.

Content of this work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license. Code snippets in examples are published under the CC0 1.0 Universal (CC0 1.0). Thanks to all the contributors.