Null object design pattern in PHP — StudySection Blog

Null object design pattern in PHP — StudySection Blog

The null object design pattern is a software design pattern in which checking for null values is replaced by using a null object. It does nothing but defines the default behavior of a service class method.

Example of the null object pattern

Below is a simple example of different types of commands as well as an application that 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:
<?php
// ...
$outputCommand = new OutputCommand();
$fileCommand = new FileCommand();
$app = new Application();
// Echo predefined string
$application->run($outputCommand);
//output will be: 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 with the command, the application accomplishes nothing, because in that case, it utilizes the null object NullCommand. Without the null object, we would have to check that in the client code, which gets problematic when more commands are introduced or circumstances grow more complex.

StudySection gives an opportunity to beginners and experts in .NET framework to go through StudySection’s .NET Certification Exam and get a .NET certification for enhancement of career in programming. If you have knowledge of the .NET framework then you can get a certificate through an online exam at StudySection.

Originally published at https://studysection.com on March 17, 2022.

--

--

The most loved online platform for eCertification in several subjects including but not limited to Software Development, Aptitude and more.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Study Section

Study Section

The most loved online platform for eCertification in several subjects including but not limited to Software Development, Aptitude and more.