Home >Backend Development >PHP Tutorial >Some summaries on the use of PHP interfaces

Some summaries on the use of PHP interfaces

伊谢尔伦
伊谢尔伦Original
2017-07-03 10:40:551627browse

PHP’s interface has been controversial from beginning to end. Some people say that the interface is very good, while others say that the interface is useless. First of all, you must understand what the criteria are for judging whether something tastes good or bad. Undoubtedly, this is compared with Java/C++. In the above example and discussion, PHP's interface is insufficient in "contract-oriented programming" and does not play its due role.

In fact, the declaration of the machine class should be in front of the plain class. The interface provides a set of specifications, which are provided by the system, then the machine class provides a set of APIs for the interface and implements them, and finally the custom class. In Java, the reason why interfaces are popular (multi-threaded runable interface, container collection interface, etc.) is because the system does the first two parts of the work for us, and programmers only need to write specific implementation classes to ensure that The interface is available and controllable.

Why use interfaces? What are the benefits of interfaces? The interface itself does not provide an implementation, only a specification. If we know that a class implements an interface, then we know the methods that can be called on the interface. We only need to know these.

In PHP, the semantics of interfaces are limited, and there are not many places to use interfaces. Interfaces in PHP can be reduced to design documents, which serve as a basic contract for the team. The code is as follows:

<?php
interface Cache
{
/**
 * describe:缓存管理,项目经理定义接口,技术人员负责实现
 */
    const maxKey = 10000;                  //最大换存量
    public function getCache($key);        //获取缓存
    public function setCache($key,$value); //设置缓存
    public function flush();               //清空缓存
}


Since PHP is weakly typed and emphasizes flexibility, it is not recommended to use interfaces on a large scale, but to only use interfaces in some "kernel" codes, because the interfaces in PHP have lost many interfaces that should have semantics. From a semantic perspective, you can use abstract classes more. As for the comparison between abstract classes and interfaces, I won’t go into details.

In addition, PHP5 has made many enhancements to the special features of Object-oriented, among which there is an attempt to SPL (labeled PHP library). Some interfaces are implemented in SPL, the most important of which is iterator Iterator interface, by implementing this interface, the object can be used in the foreach structure, so that the usage form is relatively unified. For example, there is a DirectoryIterator class in SPL. This class integrates the SplFileInfo class and implements the three interfaces Iterator, Traversable, and SeekableIterator. Then an instance of this class can obtain all the functions of the parent class SplFileInfo, and also Able to implement the operations shown in Iterator interface.

The prototype of the Iterator interface is as follows:

* current()
    This methodreturns the current index&#39;s value. You are solely responsible for tracking what thecurrent index is as the interface does not do this for you.

*key()
    This method returns the value of the current index&#39;s key. For foreach loops this is extremely important so that the key value can be populated.
    
*next()
    This method moves the internal index forward one entry.
    
*rewind()
    This method should reset the internal index to the first element.

*valid()
    This method should return true or false if there is a current element. It is called after rewind() or next().

If a class declares to implement Iterator, it must implement these five methods. If these five methods are implemented, then it can be easily implemented. Instances of the class are iterated over. Here, the reason why the DirectoryIterator class can be used is because the system has implemented the Iterator interface, so it can be used as follows:

<?php
$dir = new DirectoryIterator(dirname(FILE));

foreach ($dir as $fileInfo)
{
    if(!$fileInfo->isDir())
    {
        echo $fileInfo->getFilename(),"\t",$fileInfo->getSize(),PHP_EOL;
    }
}

It is conceivable that if you do not use the DirectoryIterator class but implement it yourself, not only the code The volume has increased, and the style during looping is no longer uniform. If the class you write also implements the Iterator interface, it can work like an Iterator.

Why can a class’s object be used as a foreach object as long as it implements the Iterator? In fact, the reason is very simple. When using foreach syntax on a PHP instance object, it will check whether the instance implements the Iterator interface. If it does, the foreach statement will be simulated through built-in methods or using methods in the implementation class. Is this the same as before? Is the implementation of the toString method mentioned similar? In fact, the toString method is a disguised implementation of the interface. The interface is like this. The interface itself does nothing. The system quietly implements the behavior of the interface internally, so as long as you implement this interface, you can use the methods provided by the interface. This is the "plug and play" idea of ​​interfaces

We all know that interfaces are a disguised implementation of multiple integrations, and when talking about inheritance, we mentioned Traits used to implement mix-ins , in fact, traits can be regarded as an enhanced version of the interface.

Look at the following code:

<?php

trait Hello
{
    public function sayHello()
    {
        echo &#39;Hello &#39;;
    }
}

trait World
{
    public function sayWorld()
    {
        echo &#39;Word&#39;;
    }
}

class MyHelloWorld
{
    use Hello, World;
    public function sayExclamationMark()
    {
        echo &#39;!&#39;;
    }
}

$o = new MyHelloWorld();

$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();

The results of the above code are as follows:

Hello Word!

MyHelloWorld here implements two traits at the same time, so that it can call two traits separately. Code snippets in Traits. As you can see from the code, Traits are very similar to interfaces. The difference is that Traits can import interfaces containing code. In a sense, traits and interfaces are a disguised implementation of "multiple integration".

Summarize several concepts about interfaces:

  • Interfaces exist as a specification and contract. As a specification, the interface should ensure usability; as a contract interface, it should ensure controllability.

  • The interface is just a statement. Once the interface keyword is used, it should be implemented. It can be implemented by the programmer (external interface) or by the system (internal interface). The interface itself does nothing, but it can tell us what it can do.

  • There are two shortcomings in the interfaces in PHP. One is that there are no contract restrictions, and the other is that there are not enough internal interfaces.

The interface is actually very simple, but the various applications of the interface are very flexible. A large part of Design Pattern also revolves around the interface.

The above is the detailed content of Some summaries on the use of PHP interfaces. 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