search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the Interface Isolation Principle (ISP) of the five object-oriented principles of PHP

This article mainly introduces the PHP object-oriented interface isolation principle (ISP), and analyzes in detail the concept, principle, usage method and related operation precautions of interface isolation. Friends in need can refer to this article

The example describes the interface isolation principle (ISP) of the five object-oriented principles of PHP. Share it with everyone for your reference, as follows:

When designing an application, if a module contains multiple sub-modules, then we should be careful to abstract the module. Assuming that the module is implemented by a class, we can abstract the system into an interface. But when adding a new module extension, if the module to be added only contains some submodules of the original system, then the system will force us to implement all methods in the interface, and we will have to write some dumb methods. Such interfaces are called fat interfaces or polluted interfaces. Using such interfaces will introduce some inappropriate behaviors into the system. These inappropriate behaviors may lead to incorrect results and may also lead to a waste of resources.

1. Interface Segregation

The Interface Segregation Principle (ISP) states that clients should not be forced to implement something they do not know how to do The interface used should group the methods in the fat interface, and then replace it with multiple interfaces, each interface serving a submodule. Simply put, it is much better to use multiple specialized interfaces than a single interface.

The main points of ISP are as follows:

1) The dependence of one class on another class should be based on the smallest interface.

ISP can achieve the goal of not forcing customers (interface usage methods) to rely on methods they do not use. The implementation class of the interface should only present a single-responsibility role (following the SRP principle)

ISP can also reduce the interaction between customers---when a customer requires new responsibilities (requires changes) and forces interface changes, the possibility of affecting other customer programs is minimal.

2) The client program should not rely on interface methods (functions) that it does not need.

The client program should depend on interface methods (functions) that it does not need. What does it depend on? Depends on the interface it requires. Provide whatever interface the client needs, and eliminate unnecessary interfaces. This requires refining the interface to ensure its purity.

For example, when inheriting, the subclass will inherit all available methods in the parent class; and some methods in the parent class may not be needed in the subclass. For example, ordinary employees and managers both inherit from the employee interface. Employees need to write work logs every day, but managers do not. Therefore, work logs cannot be used to block managers, that is, managers should not rely on the method of submitting work logs.

It can be seen that ISP and SRP have some overlap in concepts. In fact, many design patterns are conceptually overlapping, and it is even difficult to tell which design pattern a piece of code belongs to.

ISP emphasizes that the interface promises as little to the client as possible, and it must be specific. When the requirements of a certain client program change and force the interface to change, the possibility of affecting other client programs is small. This is actually a problem of interface pollution.

2. Pollution of the interface

Overly bloated interface design is pollution of the interface. The so-called interface pollution is to add unnecessary responsibilities to the interface. If the developer adds a new function to the interface just to reduce the number of interface implementation classes, this design will cause the interface to be continuously "polluted" and "fat" .

"Interface isolation" is actually the principle of customized service design. Use multiple inheritance of interfaces to combine different interfaces to provide external combination functions --- to achieve "services on demand".

The interface needs to be dismantled, but it cannot be dismantled too finely. There must be a standard, which is high cohesion. The interface should have some basic functions and be able to uniquely complete a basic task.

In practical applications, you will encounter the following problems: For example, I need a DAO implementation that can adapt to multiple types of databases. Then I should first implement a database operation interface, which stipulates some basic database operations. Methods, such as connecting to the database, adding, deleting, modifying, and querying, closing the database, etc. This is a minimally functional interface. For some methods that are unique to MySQL but do not exist in other databases or are of different nature, such as MySQL's pconnect method that may be used in PHP, the same concept as this method does not exist in other databases, so this method does not exist. It should appear in this basic interface, so what basic methods should this basic interface have? PDO has told you so.

PDO is an abstract database interface layer, which tells us what basic methods a basic database operation interface should implement. The interface is a high-level abstraction, so the methods in the interface should be universal, basic, and not easy to change.

There is another question, how should those unique methods be implemented? According to the ISP principle, these methods can exist in another interface, allowing this "heterogeneous" to implement both interfaces at the same time.

For interface pollution, you can consider these two processing methods:

Use delegation to separate interfaces.

Use multiple inheritance to separate interfaces.

In the delegation mode, two objects participate in processing the same request. The object that accepts the request delegates the request to another object for processing. Delegation is applied in strategy mode, proxy mode, etc. concept.

Let’s take a look at the examples

Have you ever encountered a very “fat” interface?

For example: there is an interface related to animals, the code is as follows:

<?php
interface Animal{
  public function walk();
  public function speak();
}

Dog is a concrete example of this interface Implementation:

<?php
require_once "animal.php";
class Dog implements Animal{
  public function walk(){
    echo "dogs can walk";
  }
  public function speak(){
    echo "dogs can speak";
  }
}

ok, now we want to create a fish that can swim, what should we do? We must modify the interface, which will also affect the implementation of the dog class, and fish also needs to implement the walk and speak methods, as shown in the following code:

Animal interface class:

<?php
interface Animal{
  public function walk();
  public function speak();
  public function swim();
}

dog class:

<?php
require_once "animal.php";
class Dog implements Animal{
  public function walk(){
    echo "dogs can walk";
  }
  public function speak(){
    echo "dogs can speak";
  }
  public function swim(){
  }
}

fish class:

<?php
require_once "animal.php";
class Fish implements Animal{
  public function walk(){
  }
  public function speak(){
  }
  public function swim(){
    echo "fish can swim";
  }
}

At this time, the Animal interface class shows the characteristics of a "fat" interface. The so-called fat interface actually means that the interface defines methods that are not required by all implementation classes. Just like the Animal interface class, some animals cannot swim, some animals cannot walk, and some animals cannot fly. If these methods are written in an Animal interface class, then later expansion and maintenance will be a disaster.

So, how to solve the above problems?

It’s very simple, just refine the interface and split the Animal interface class into three interface classes:

animalCanWalk interface class:

<?php
interface animalCanSpeak{
  public function speak();
}

AnimalCanSwim interface class:

<?php
interface AnimalCanSwim{
  public function swim();
}

animalCanSpeak interface class:

<?php
interface animalCanSpeak{
  public function speak();
}

After defining these interface classes, the implementation of dog and fish will be much easier,

<?php
require_once "animalCanSpeak.php";
require_once "animalCanWalk.php";
class Dog implements animalCanSpeak,animalCanWalk{
  public function walk(){
    echo "dogs can walk";
  }
  public function speak(){
    echo "dogs can speak";
  }
}

<?php
require_once "animalCanSwim.php";
class Fish implements AnimalCanSwim{
  public function swim(){
    echo "fish can swim";
  }
}

To summarize:

The concept of Interface Segregation Principle (ISP): Use multiple specialized interfaces instead of A single overall interface, i.e. the client should not rely on interfaces it does not need.

When using the interface isolation principle, we need to pay attention to controlling the granularity of the interface. The interface cannot be too small. If it is too small, it will lead to a proliferation of interfaces in the system, which is not conducive to maintenance; the interface should not be too large or too small. A large interface will violate the interface isolation principle, have poor flexibility, and be very inconvenient to use. Generally speaking, an interface should only contain methods customized for a certain type of user, and clients should not be forced to rely on methods they do not use.

Related recommendations:

Detailed explanation of the open-closed principle (OCP) of the five object-oriented principles of PHP

The above is the detailed content of Detailed explanation of the Interface Isolation Principle (ISP) of the five object-oriented principles of PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools