Table of Contents
Overview
Target Audience
What is an interface?
Using interfaces in PHP
结论
Home Backend Development PHP Tutorial An article explaining the meaning of interfaces and how to use interfaces to write high-quality PHP code

An article explaining the meaning of interfaces and how to use interfaces to write high-quality PHP code

Nov 08, 2021 pm 03:43 PM
interface php

Overview

One important thing in coding is to make sure that your code is readable, maintainable, extensible, and easy to test. One way we can improve these problems is to use interfaces.

Target Audience

This article is aimed at developers who have a basic understanding of OOP (object oriented programming) concepts and inheritance in PHP. If you know how to use inheritance in PHP, then this article It will be easier to understand.

What is an interface?

Basically, an interface describes "what a class should do." Interfaces are used to ensure that any class that implements the interface contains the public methods specified by the interface.

Interface can :

  • be used to define public methods in a class.
  • is used to define constants in classes.

Interface cannot :

  • be instantiated individually.
  • is used to define private or protected methods in a class.
  • is used to define attributes in the class.

Interface is used to define the public methods that should be included in a class. What needs to be remembered is that the interface only defines the method name, parameters and return value, but does not include the method body. This is because interfaces are only used to define communication between objects, not to define the specific behavior of communication between classes. To give a little context, this example shows an example interface that defines several public methods:

interface DownloadableReport
{
    public function getName(): string;

    public function getHeaders(): array;

    public function getData(): array;
}
Copy after login
Copy after login

According to php.net, interfaces have two main purposes:

  1. Allows developers to create objects of different classes that can be used interchangeably because they implement the same interface. A common example is multiple database access services, multiple payment gateways or different caching strategies. Different implementations can be replaced without any changes to the code that uses them.
  2. Allows a function or method to accept parameters that conform to the interface and operate on them, without caring about what else the object can do or how it is implemented. These interfaces are often named Iterable, Cacheable, Renderable, etc. to describe the meaning of the behavior. [Recommended learning: "PHP Video Tutorial"]

Using interfaces in PHP

The interface is a very important part of the OOP (Object-Oriented Programming) code . They allow us to decouple our code and improve scalability. As an example, let's look at the following class:

class BlogReport
{
    public function getName(): string
    {
        return 'Blog report';
    }
}
Copy after login

As you can see, we have defined a class with a method that returns a string. By doing this, we have determined the behavior of the method, so we can see how getName() builds the returned string. However, let's say we call this method from code in another class. The other class doesn't care how the string is constructed, it only cares whether it is returned. For example, let's see how to call this method in another class:

class ReportDownloadService
{
    public function downloadPDF(BlogReport $report)
    {
        $name = $report->getName();

        // 在这里下载文件...
    }
}
Copy after login

Although the above code already works, let's imagine what if we now want to call it in UserReport Add a method to download user reports to the class. Of course, we cannot use the existing methods in ReportDownloadService because we have been forced to pass in only one BlogReport class. Therefore, we have to rename the existing method and add a new one. Like this:

class ReportDownloadService
{
    public function downloadBlogReportPDF(BlogReport $report)
    {
        $name = $report->getName();

        // 在这下载文件...
    }

    public function downloadUsersReportPDF(UsersReport $report)
    {
        $name = $report->getName();

        // 在这下载文件...
    }
}
Copy after login

Although you can't actually see it, we assume that the rest of the methods in the above class use the same code to build the download. We can promote public code to methods, but we will still have some public code. In addition to this, we have multiple entries into this class with almost identical code. This may result in additional work when trying to extend the code or add testing functionality in the future.

For example, we create a new AnalyticsReport; we now need to add a new downloadAnalyticsReportPDF() method to this class. At this point you may observe that the file is growing rapidly. This is a great time to use interfaces.

We start by creating an interface. We are going to create an interface called DownloadableReport and define it like this:

interface DownloadableReport
{
    public function getName(): string;

    public function getHeaders(): array;

    public function getData(): array;
}
Copy after login
Copy after login

We are now going to change BlogReport and UsersReport to implement DownloadableReport interface, as shown below. I intentionally wrote the wrong UsersReport code to demonstrate something.

class BlogReport implements DownloadableReport
{
    public function getName(): string
    {
        return '博客报告';
    }

    public function getHeaders(): array
    {
        return ['头在这'];
    }

    public function getData(): array
    {
        return ['报告的数据在这里'];
    }
}
Copy after login
class UsersReport implements DownloadableReport
{
    public function getName()
    {
        return ['用户报告'];
    }

    public function getData(): string
    {
        return '报告的数据在这里';
    }
}
Copy after login

If we try to run this code, we will get an error because:

  1. 找不到 getHeaders() 方法。
  2. getName() 方法返回类型在接口中定义的方法返回值类型中。
  3. getData() 方法定义了返回类型,但和接口中定义的返回类型不同。

因此,要让 UsersReport 正确地实现 DownloadableReport 接口,我们需要作如下变动:

class UsersReport implements DownloadableReport
{
    public function getName(): string
    {
        return '用户报告';
    }

    public function getHeaders(): array
    {
       return [];
    }

    public function getData(): array
    {
        return ['报告的数据在这里'];
    }
}
Copy after login

现在我们两个报告类都实现了相同的接口,我们可以像这样更新我们的 ReportDownloadService

class ReportDownloadService
{
    public function downloadReportPDF(DownloadableReport $report)
    {
        $name = $report->getName();

        // 在这下载文件
    }

}
Copy after login

现在我们向 downloadReportPDF() 方法传入了 UsersReport 或 BlogReport 对象,没有任何错误出现。这是因为我们现在知道了报告类所需要的必要方法,并且报告类会按照我们预期的类型返回数据。

向方法传入接口,而不是向类传入接口,这样的结果使得 ReportDownloadService 和报告类产生松散耦合,这根据的是方法做什么,而不是如何做

如果我们想要创建一个新的 AnalyticsReport,我们需要让它实现相同的接口,然后它就会允许我们将报告类实例传入相同的 downloadReportPDF() 方法中,而不用添加其他新的方法。如果你正在构建自己的应用或框架,想要让其他开发人员有创建给他们自己的类的功能,这将非常有用。举个例子,在 Laravel 中,你可以通过实现 Illuminate\Contracts\Cache\Store 接口来创建自定义的缓存类。

除了使用接口来改进代码外,我更倾向于喜欢接口的「代码即文档」特性。举个例子,如果我想要知道一个类能做什么和不能做什么,我更喜欢在查看类之前先查看接口。它会告诉我所有可调用的方法,而不需要关心这些方法具体是怎么运行的。

对于像我这样的 Laravel 开发者来说,值得注意的一件事是,你会经常看到 接口 interface契约 contract 交替使用。根据 Laravel 文档,「Laravel 的契约是一组定义了框架提供的核心服务的接口」。因此,契约是一个接口,但接口不一定是契约。通常来说,契约只是框架提供的一个接口。有关契约的更多内容,我建议阅读一下 文档,因为我认为它在契约的理解和使用途径上有很好的见解。

结论

阅读本文后,我们希望你能简要地了解到了什么是接口,如何在 PHP 中使用接口,以及使用接口的好处。

对于我的 Laravel 开发者读者们,我下周会更新一篇新的博文,讲解如何在 Laravel 中使用接口实现桥接模式。如果你感兴趣,可以订阅我的网站更新通知,这样当我更新时,你就会收到通知。

如果这篇文章有助于你理解 PHP 接口,我期待在评论区听到你的声音。继续去创造令人惊叹的作品吧!

非常感谢  Aditya Kadam 、 Jae Toole 和 Hannah Tinkler 帮助我校对和改进这篇文章。

原文地址:https://dev.to/ashallendesign/using-interfaces-to-write-better-php-code-391f

译文地址:https://learnku.com/php/t/62228

The above is the detailed content of An article explaining the meaning of interfaces and how to use interfaces to write high-quality PHP code. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
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

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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.

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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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 vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles