Home >Backend Development >PHP Tutorial >PHP Master | The Null Object Pattern - Polymorphism in Domain Models
Core points
Although it does not fully comply with the specifications, it can be said that orthogonality is the essence of a software system based on the principle of "good design", in which the modules are decoupled from each other, making the system less prone to rigid and fragile problems. Of course, it is easier to talk about the advantages of orthogonal systems than actually running production systems; this process is usually a pursuit of utopia. Even so, it is by no means a utopian concept to achieve highly decoupled components in a system. Various programming concepts such as polymorphism allow design of flexible programs, whose parts can be switched at runtime, and their dependencies can be expressed in abstract forms rather than concrete implementations. I would say that the old motto of “interface-oriented programming” has been widely adopted over time, whether we are implementing infrastructure or application logic. However, when stepping into the realm of domain models, the situation is very different. Frankly, this is a predictable scenario. After all, why should an interrelated network of objects (which have data and behaviors limited by well-defined business rules) be polymorphic? It doesn't make much sense in itself. However, there are some exceptions to this rule, which may eventually apply to this situation. The first exception is the use of a virtual proxy, which is effectively the same interface as the actual domain object implements. Another exception is the so-called "null case", which is a special case where an operation may end up assigning or returning null values instead of filling in a well-filled entity. In traditional non-polymorphic approaches, the user of the model must check these "harmful" null values and gracefully handle the condition, resulting in an explosion of conditional statements throughout the code. Fortunately, this seemingly confusing situation is easily solved by simply creating a multi-branch implementation of the domain object that will implement the same interface as the object in question, except that its method does nothing, so the client will be The code is freed from repeatedly checking ugly null values while performing an operation. Not surprisingly, this approach is a design pattern called empty objects that brings the advantages of polymorphism to the extreme. In this article, I will demonstrate the benefits of this pattern in several cases and show you how they are closely attached to polymorphic methods.
Treat non-polymorphic conditions
As one would expect, there are several ways to try when showing the advantages of empty object patterns. A particularly straightforward approach I found is to implement a data mapper that may end up returning null values from a general-purpose finder. Suppose we have successfully created a skeleton domain model that consists of only one user entity. The interface and its class are as follows:
<code class="language-php"><?php namespace Model; interface UserInterface { public function setId($id); public function getId(); public function setName($name); public function getName(); public function setEmail($email); public function getEmail(); }</code>
<code class="language-php"><?php namespace Model; class User implements UserInterface { private $id; private $name; private $email; public function __construct($name, $email) { $this->setName($name); $this->setEmail($email); } public function setId($id) { if ($this->id !== null) { throw new BadMethodCallException( "The ID for this user has been set already."); } if (!is_int($id) || $id throw new InvalidArgumentException( "The ID for this user is invalid."); } $this->id = $id; return $this; } public function getId() { return $this->id; } public function setName($name) { if (strlen($name) 30) { throw new InvalidArgumentException( "The user name is invalid."); } $this->name = $name; return $this; } public function getName() { return $this->name; } public function setEmail($email) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new InvalidArgumentException( "The user email is invalid."); } $this->email = $email; return $this; } public function getEmail() { return $this->email; } }</code>
The User class is a reactive structure that implements some mutators/accessors to define some user data and behavior. With this constructed domain class, we can now go a step further and define a basic data mapper that isolates our domain model and data access layer from each other.
<code class="language-php"><?php namespace ModelMapper; use LibraryDatabaseDatabaseAdapterInterface, ModelUser; class UserMapper implements UserMapperInterface { private $adapter; public function __construct(DatabaseAdapterInterface $adapter) { $this->adapter = $adapter; } public function fetchById($id) { $this->adapter->select("users", array("id" => $id)); if (!$row = $this->adapter->fetch()) { return null; } return $this->createUser($row); } private function createUser(array $row) { $user = new User($row["name"], $row["email"]); $user->setId($row["id"]); return $user; } }</code>
The first thing that should appear is that the mapper's fetchById() method is a naughty in the block, because it effectively returns null when no user in the database matches the given ID. For obvious reasons, this clumsy condition makes the client code have to work hard to check the null value every time it calls the mapper's finder.
<code class="language-php"><?php use LibraryLoaderAutoloader, LibraryDatabasePdoAdapter, ModelMapperUserMapper; require_once __DIR__ . "/Library/Loader/Autoloader.php"; $autoloader = new Autoloader; $autoloader->register(); $adapter = new PdoAdapter("mysql:dbname=test", "myusername", "mypassword"); $userMapper = new UserMapper($adapter); $user = $userMapper->fetchById(1); if ($user !== null) { echo $user->getName() . " " . $user->getEmail(); }</code>
At first glance, there will be no problem, just check it in one place. But if the same line appears in multiple page controllers or service layers, will you bump into a brick wall? Before you realize it, the seemingly innocent null returned by the mapper will produce a lot of repetitive conditions, which is a bad omen of poor design.
Remove condition statements from client code
However, there is no need to worry, because this is exactly the case where the empty object pattern shows why polymorphism is a godsend. If we want to get rid of those annoying conditional statements once and for all, we can implement the polymorphic version of the previous User class.
<code class="language-php"><?php namespace Model; class NullUser implements UserInterface { public function setId($id) { } public function getId() { } public function setName($name) { } public function getName() { } public function setEmail($email) { } public function getEmail() { } }</code>
If you expect a complete entity class to package all kinds of decorations, you're probably very disappointed. The "null" version of the entity complies with the corresponding interface, but the method is an empty wrapper and there is no actual implementation. While the existence of the NullUser class obviously doesn't bring us anything that deserves praise, it is a concise structure that allows us to throw all previous conditional statements into the trash. Want to see how it is implemented? First, we should do some pre-work and reconstruct the data mapper so that its finder returns an empty user object instead of an empty value.
<code class="language-php"><?php namespace ModelMapper; use LibraryDatabaseDatabaseAdapterInterface, ModelUser, ModelNullUser; class UserMapper implements UserMapperInterface { private $adapter; public function __construct(DatabaseAdapterInterface $adapter) { $this->adapter = $adapter; } public function fetchById($id) { $this->adapter->select("users", array("id" => $id)); return $this->createUser($this->adapter->fetch()); } private function createUser($row) { if (!$row) { return new NullUser; } $user = new User($row["name"], $row["email"]); $user->setId($row["id"]); return $user; } }</code>The mapper's createUser() method hides a tiny condition because it is now responsible for creating an empty user when the ID passed to the finder does not return a valid user. Even so, this nuanced cost not only saves the work of client code doing a lot of repeated checks, but also turns it into a loose consumer that won't complain when it has to deal with empty users.
<code class="language-php"><?php namespace Model; interface UserInterface { public function setId($id); public function getId(); public function setName($name); public function getName(); public function setEmail($email); public function getEmail(); }</code>
The main disadvantage of this polymorphic approach is that any application that uses it will become too loose because it never crashes when dealing with invalid entities. In the worst case, the user interface will only show some blank lines, but nothing really noisy makes us disgusted. This is especially obvious when scanning for the current implementation of the early NullUser class. Even if it is feasible, not to mention the recommended one, it can also encapsulate logic in empty objects while keeping its polymorphism unchanged. I can even say that empty objects are perfect for encapsulating default data and behaviors that should be exposed to client code only in a few special cases. If you are ambitious enough and want to try this concept with a simple empty user object, the current NullUser class can be refactored as follows:
<code class="language-php"><?php namespace Model; class User implements UserInterface { private $id; private $name; private $email; public function __construct($name, $email) { $this->setName($name); $this->setEmail($email); } public function setId($id) { if ($this->id !== null) { throw new BadMethodCallException( "The ID for this user has been set already."); } if (!is_int($id) || $id throw new InvalidArgumentException( "The ID for this user is invalid."); } $this->id = $id; return $this; } public function getId() { return $this->id; } public function setName($name) { if (strlen($name) 30) { throw new InvalidArgumentException( "The user name is invalid."); } $this->name = $name; return $this; } public function getName() { return $this->name; } public function setEmail($email) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new InvalidArgumentException( "The user email is invalid."); } $this->email = $email; return $this; } public function getEmail() { return $this->email; } }</code>
The enhanced version of NullUser is slightly more expressive than its quiet predecessor, as its getter provides some basic implementations to return some default messages when requesting an invalid user. While trivial, this change has a positive impact on how client code handles empty users, as this time users at least know that some problems arise when they try to extract non-existent users from storage. This is a good breakthrough, not only showing how to implement empty objects that aren't actually empty at all, but also how easy it is to move logic inside relevant objects based on specific needs.
Conclusion
Some might say that implementing empty objects is troublesome, especially in PHP, where core concepts of OOP (such as polymorphism) are significantly underestimated. They are right to some extent. Nevertheless, the gradual adoption of trustworthy programming principles and design patterns, as well as the level of maturity that the language object model has reached, is to steadily move forward and start using some of the “luxury goods” that were considered complex and unrealistic notions not long ago Provides all the necessary basis. The null object pattern falls into this category, but its implementation is so simple and elegant that it is hard not to find it attractive when clearing duplicate null checks in client code. Pictures from Fotolia
(Due to space limitations, the FAQ part in the original text is omitted here.)
The above is the detailed content of PHP Master | The Null Object Pattern - Polymorphism in Domain Models. For more information, please follow other related articles on the PHP Chinese website!