Home Backend Development PHP Tutorial PHP Master | The Null Object Pattern - Polymorphism in Domain Models

PHP Master | The Null Object Pattern - Polymorphism in Domain Models

Feb 25, 2025 pm 02:53 PM

PHP Master | The Null Object Pattern - Polymorphism in Domain Models

Core points

  • The empty object pattern is a design pattern that uses polymorphism to reduce conditional code, making the code more concise and easy to maintain. It provides a non-functional object that can replace the real object, thus eliminating the need for null value checks.
  • Empty object mode can be used in conjunction with other design modes, such as factory mode creating and returning empty objects, or policy mode changing the behavior of an object at runtime.
  • The potential disadvantage of the empty object pattern is that it may lead to the creation of unnecessary objects and increase memory usage. It may also make the code more complicated because additional classes and interfaces are required.
  • Implementing the empty object pattern requires creating an empty object class that implements the same interface as the real object. This empty object provides a default implementation for all methods in the interface, allowing it to replace the real object. This makes the code more robust and less prone to errors.

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:

<?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();
}
Copy after login
Copy after login
<?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;
    }
}
Copy after login
Copy after login

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.

<?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;
    }
}
Copy after login

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.

<?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();
}
Copy after login

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.

<?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() { }
}
Copy after login

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.

<?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; 
    }
}
Copy after login
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.

<?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();
}
Copy after login
Copy after login

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:

<?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;
    }
}
Copy after login
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain Arrow Functions (short closures) introduced in PHP 7.4. Explain Arrow Functions (short closures) introduced in PHP 7.4. Apr 06, 2025 am 12:01 AM

The arrow function was introduced in PHP7.4 and is a simplified form of short closures. 1) They are defined using the => operator, omitting function and use keywords. 2) The arrow function automatically captures the current scope variable without the use keyword. 3) They are often used in callback functions and short calculations to improve code simplicity and readability.

See all articles