Author - StudySection Post Views - 345 views
Object Design

Null Object Design Pattern in PHP

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.

Leave a Reply

Your email address will not be published.