PHP Open Closed Principle of Five Object Oriented Principles of OCP Detailed Explanation

  • 2021-09-20 19:45:27
  • OfStack

In this paper, the Open-Closed Principle (OCP), one of the five object-oriented principles of PHP, is described with examples. Share it for your reference, as follows:

1. What is "open-closed"

With the increasing scale of software system, the complexity of maintenance and modification of software system is increasing. This dilemma urges French engineering academician Bertrand Meyer to put forward the principle of "open-closed" (Open-Close Principle, OCP) in 1998. The basic idea of this principle is:

The behavior of the Open (Open for extendtion) module must be open and extensible, not rigid.

Close (Closed for modification) should not affect or massively affect existing modules when extending the functionality of modules.

In other words, developers are required to extend the software functions of the application system without modifying the existing codes (source code or binary code). To sum up in one sentence, a module should be developed in terms of extensibility and closed in terms of changeability.

From life, the easiest example to think of is the computer. We can easily expand the functions of the computer, and only need to connect with different devices through the interface.

Open-closed can improve the scalability and maintainability of the system, but this is also relative. It is impossible to completely open a computer, and some devices and functions must be kept stable to reduce maintenance difficulties. To realize a new feature, you must upgrade your hardware or replace it with a higher-performance computer. Taking the multimedia playing software in the computer as an example, as a player, it should have some basic and general functions, such as opening multimedia files, stopping playing, fast forward, volume adjustment and so on. However, no matter what player it is, no matter what playing platform it is, the player designed according to this principle should have a unified style and operating habits, and no matter which one is used, it should ensure that the author can get started quickly.

Take the player as an example, first define an abstract interface, and the code is as follows.


interface process
{
  public function process();
}

Then, this interface is extended to implement decoding and output functions, as follows


class playerencode implements process
{
  public function process()
  {
    echo "encode",PHP_EOL;
  }
}
class playeroutput implements process
{
  public function process()
  {
    echo "ouput",PHP_EOL;
  }
}

For various functions of the player, it is open here. As long as you follow the agreement and realize the process interface, you can add new functional modules to the player. Only decoding and output modules are realized here, and more new modules can be added according to requirements.

Next, define the thread high scheduling manager of the player. Once the player 1 receives the notification (which can be an external click behavior or an internal notify behavior), it will call back the actual thread processing. The code is as follows


class playProcess
{
  private $message = null;
  public function __construct() {}
  public function callback(event $event)
  {
    $this->message = $event->click();
    if($this->message instanceof process)
    {
      $this->message->process();
    }
  }
}

Specific products come out, here define an MP4 class, this class is relatively closed, which defines the event processing logic, the code is as follows


class mp4
{
  public function work()
  {
    $playProcess = new playProcess();
    $playProcess->callback(new event('encode'));
    $playProcess->callback(new event('output'));
  }
}

Finally, it is the event sorting processing class, which is responsible for sorting events, judging users or internal behaviors, and generating correct "threads" for the player's built-in purebred manager to schedule. The code is as follows


class event
{
  private $m;
  public function __construct($me)
  {
    $this->m = $me;
  }
  public function click()
  {
    switch($this->m)
    {
      case 'encode';
        return new playerencode();
        break;
      case 'output':
        return new playeroutput();
        break;
    }
  }
}

Finally, run the next code


$mp4 = new mp4;
$mp4->work();

The running results are as follows:

encode ouput

2. How to abide by the open-closed principle

The core of opening-closing is to program abstractions rather than concrete ones, because abstractions are relatively stable. Let the class rely on fixed abstractions, and such modifications are closed; Through object-oriented inheritance and polymorphism mechanism, we can realize the inheritance of abstract body, change its inherent behavior by overwriting its method, and realize new extension method, so it is open for extension.

1) Apply the ideas of "abstraction" and "encapsulation" in design.

One aspect is to find out all kinds of possible "variables" in the software system and encapsulate them.

On the other hand, a variable factor should not be scattered among multiple different code modules, but should be encapsulated in an object.

2) Applying interface-oriented programming in the realization of system function programming.

When the requirements change, a new implementation class of the interface can be provided to adapt to the changes.

Interface-oriented programming requires functional classes to implement interfaces and objects to be declared as interface types. In the design mode, the decoration mode obviously uses OCP.

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: