


[Modern PHP] Chapter 2 New Features 2 Interface-based Programming
Interface-based programming
As a PHP programmer, learning how to program based on interfaces has changed my life and greatly improved my ability to improve my projects by integrating third-party PHP components. Interfaces are not a new feature, but they are important features that you must understand and use in your daily work.
So what exactly is the interface of PHP? An interface is a contract between two PHP objects. When one object calls another object, it does not need to know what the other party is, but only needs to know what the other party can do. Interfaces can reduce the coupling of our code's dependencies, allowing our code to call any third-party code that implements the desired interface. We only need to care about whether the third-party code implements the interface, and we don't need to care at all about how the third-party code implements these interfaces. Let's look at a real-life example.
Suppose I go to Miami, Florida to attend the Sunshine PHP Developer Conference. I wanted to explore the city so I went straight to the local car rental agency. They had a modern compact car, a Subaru station wagon and a Bugatti Veyron (to my surprise). I knew I just wanted some form of transportation to get around town, and all three of these vehicles would fit my needs. But each car is so different. The Hyundai Accent is not bad, but I like something a little more dynamic. I don’t have kids, so the station wagon is still a bit big. So, okay, just choose Bugatti.
The reality is that I can drive any of these three cars because they all share a common, known interface. Every car has a steering wheel, a gas pedal, a brake pedal and turn signals, and every car uses gasoline as fuel. But the Bugatti's power is so powerful that I can't handle it, but the driving interface of the modern car is exactly the same. Because all three cars share the same known interface, I have the opportunity to choose the model I like better (to be honest, I will probably choose Hyundai in the end).
The same concept exists in the object-oriented aspect of PHP. If my code uses objects of a specific class (representing a specific implementation), then the functionality of my code becomes very limited, because it can only use objects of that class forever. However, if my code is going to use an interface, my code will immediately know how to use any object that implements the interface. My code doesn't care at all about how the interface is implemented. My code only cares about whether the object implements the interface. Let's use an example to explain it all.
Suppose we have a PHP class named DocumentStore that can get data from different data sources. It can get HTML from a remote address, read data from the document stream, and get terminal commands. line output. Each document saved in a DocumentStore instance has a unique ID. Example 2-6 shows the DocumentStore class.
Example 2-6 Definition of DocumentStore class
class DocumentStore { protected $data = []; public function addDocument(Documentable $document) { $key = $document->getId(); $value = $document->getContent(); $this->data[$key] = $value; } public function getDocuments() { return $this->data; } }
If the addDocument method only receives instances of the Documentable class as parameters, how can we achieve the function described above? Very good at observation. In fact, Documentable is not a class, but an interface. Take a look at the definition of the interface in Example 2-7
Example 2-7 The definition of Documentable interface
interface Documentable { public function getId(); public function getContent(); }
In the definition of the interface we can see any implementation Objects of the Documentable interface must define a public getId() method and a public getContent() method.
So what are the benefits of doing this? The advantage is that we can construct multiple document acquisition classes with different functions. Example 2-8 shows an interface implementation that obtains HTML from a remote address through curl.
Example 2-8 Definition of HtmlDocument class
<?php class HtmlDocument implements Documentable { protected $url; public function __construct($url) { $this->url = $url; } public function getId() { return $this->url; } public function getContent() { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_MAXREDIRS, 3); $html = curl_exec($ch); curl_close($ch); return $html; } }
Another implementation (Example 2-9) can read the data stream from a given resource.
Example 2-9 Definition of StreamDocument class
<?php class StreamDocument implements Documentable { protected $resource; protected $buffer; public function __construct($resource, $buffer = 4096) { $this->resource = $resource; $this->buffer = $buffer; } public function getId() { return 'resource-' . (int)$this->resource; } public function getContent() { $streamContent = ''; rewind($this->resource); while (feof($this->resource) === false) { $streamContent .= fread($this->resource, $this->buffer); } return $streamContent; } }
The last implementation (Example 2-10) can execute a terminal command and obtain the execution results
Example 2-10 Definition of CommandOutputDocument class
<?php class CommandOutputDocument implements Documentable { protected $command; public function __construct($command) { $this->command = $command; } public function getId() { return $this->command; } public function getContent() { return shell_exec($this->command); } }
Example 2-11 shows how we use the DocumentStore class to operate the three document collection classes that implement the Documentable interface
Example 2-11 DocumentStore
<?php $documentStore = new DocumentStore(); // Add HTML document $htmlDoc = new HtmlDocument('http://php.net'); $documentStore->addDocument($htmlDoc); // Add stream document $streamDoc = new StreamDocument(fopen('stream.txt', 'rb')); $documentStore->addDocument($streamDoc); // Add terminal command document $cmdDoc = new CommandOutputDocument('cat /etc/hosts'); $documentStore->addDocument($cmdDoc); print_r($documentStore->getDocuments());
The biggest highlight of this is the HtmlDocument, StreamDocument and CommandOutputDocument classes Except for the consistent interface, other aspects are completely different.
Today, programming interfaces creates more flexible code, and we no longer care about the specific implementation, but leave these tasks to others. More and more people (such as your colleagues, users of your open source projects, or developers you have never met) can write code that works seamlessly with you, and they just need to understand Just interface.
The above introduces [Modern PHP] Chapter 2 New Features 2 Interface-based Programming, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

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 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.

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 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.

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

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.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor