[ModernPHP] Chapter 2 new feature 2 interface-based programming

Source: Internet
Author: User
: This article mainly introduces [ModernPHP] Chapter 2 new feature 2 interface-based programming. For more information about PHP tutorials, see. Interface-based programming

As a PHP programmer, learning how to program based on interfaces has changed my life and greatly improved my project capabilities by integrating third-party PHP components. Interfaces are not new functions, but they are important features that you must understand and use in your daily work.

So what is the PHP interface? An interface is a contract between two PHP Objects. When an object calls another object, it does not need to know what the other object is, but what the other object can do. Interfaces can reduce the coupling of code dependencies and allow 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 interfaces, rather than how the third-party code implements these interfaces. Let's look at a real example.

Suppose I went to Miami, Florida to attend the Sunshine PHP developer conference. I want to visit the city, so I went directly to the local car rental company. They have a modern compact car, a Subaru wagon, and a bugatyr (which surprised me too ). I know that I just want to use a certain means of transportation to visit the city. All three cars can meet my needs. But every car is so different. Modern Gentleman is good, but I like more dynamic. I have no children, so the wagon is a little bigger. So, select bugatd.

The reality is that I can drive any of these three cars, because they all share public and known interfaces. Each car has a steering wheel, a pedal, a brake pedal, and a steering light. each car uses gasoline as fuel. But Bugatti is so powerful that I cannot control it, but modern cars have the same driving interface as it. Because all three cars share the same known interface, but I have the opportunity to choose my preferred model (to be honest, I may still choose the modern one ).

PHP has the same object-oriented concept. If my code uses an object of a specific class (representing a specific implementation), the functions of my code are also very limited, because it can only use the 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 this interface. My code does not need to care about how interfaces are implemented. my code only cares about whether objects have implemented interfaces. let's use an example to explain all this clearly.

Suppose we have a PHP class named DocumentStore that can get data from different data sources. it can get HTML from a remote address or read data from the document stream, you can also obtain the command line output of the terminal. Each document stored in the DocumentStore instance has a unique ID. Example 2-6 shows the DocumentStore class.

Example 2-6 DocumentStore class definition

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 the Documentable class instance as a parameter, how can it implement the previously described function? Good observation. In fact, Documentable is not a class but an interface. let's take a look at the interface definition in example 2-7.

Example 2-7 Documentable Interface Definition

interface Documentable{    public function getId();    public function getContent();}

In the interface definition, we can see that any object implementing the Documentable interface must define a public getId () method and a public getContent () method.

So what are the benefits of doing so? The advantage is that we can construct multiple document acquisition classes with different functions. Example 2-8 shows an interface for obtaining HTML from a remote address through curl.

Example 2-8 definitions of the HtmlDocument class

 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 data streams from a given resource.

Example 2-9 definition of the StreamDocument class

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

Example 2-10 definition of the CommandOutputDocument class

 command = $command;    }    public function getId()    {        return $this->command;    }    public function getContent()    {        return shell_exec($this->command);    }}

Example 2-11 shows how to use the DocumentStore class to operate on the three file collection classes that implement the Documentable interface.

Example 2-11 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 that the HtmlDocument, StreamDocument, and CommandOutputDocument classes are completely different except for the same interface.

Today, more flexible code has been created by programming interfaces. Instead of concerning specific implementations, we have handed over the work 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 can seamlessly connect with each other, they only need to understand the interface.

The above introduces [Modern PHP] Chapter 2 new features 2 interface-based programming, including some content, and hope to help those who are interested in PHP tutorials.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.