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

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;
    }
}

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();
}

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() { }
}

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; 
    }
}
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();
}

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;
    }
}

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

PHP Tutorial
1509
276
PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

See all articles