From ceeab58eb9df78820a12588f1bef635693bc3cb9 Mon Sep 17 00:00:00 2001 From: Trismegiste Date: Mon, 13 May 2013 21:49:33 +0200 Subject: [PATCH] add a simple example with a null logger --- NullObject/LoggerInterface.php | 16 ++++++++++++++ NullObject/NullLogger.php | 38 ++++++++++++++++++++++++++++++++++ NullObject/PrintLogger.php | 20 ++++++++++++++++++ NullObject/Service.php | 30 +++++++++++++++++++++++++++ 4 files changed, 104 insertions(+) create mode 100644 NullObject/LoggerInterface.php create mode 100644 NullObject/NullLogger.php create mode 100644 NullObject/PrintLogger.php create mode 100644 NullObject/Service.php diff --git a/NullObject/LoggerInterface.php b/NullObject/LoggerInterface.php new file mode 100644 index 0000000..2c6ed97 --- /dev/null +++ b/NullObject/LoggerInterface.php @@ -0,0 +1,16 @@ + less test cases + * + * The purpose : every time you have a method which returns an object or null, + * you should return an object or a "NullObject". With NullObject, you don't need + * statement like "if (!is_null($obj)) { $obj->callSomething(); }" anymore. + * + * In this case, this a logger which does nothing. Other examples : + * - null logger of symfony profiler + * - null output in symfony/console + * - null handler in a Chain of Responsiblities pattern + * - null command in a Command pattern + * + * Performance concerns : ok there is a call for nothing but we spare an "if is_null" + * I didn't run a benchmark but I think it's equivalent. + */ +class NullLogger implements LoggerInterface +{ + + public function log($str) + { + + } + +} \ No newline at end of file diff --git a/NullObject/PrintLogger.php b/NullObject/PrintLogger.php new file mode 100644 index 0000000..4640ca4 --- /dev/null +++ b/NullObject/PrintLogger.php @@ -0,0 +1,20 @@ +logger = $log; + } + + public function doSomething() + { + // no more check "if (!is_null($this->logger))..." with the NullObject pattern + $this->logger->log('We are in ' . __METHOD__); + // something to do... + } + +} \ No newline at end of file