Home > Backend Development > PHP Tutorial > Detailed explanation of the interface of the PHP SPL standard library, splinterface_PHP tutorial

Detailed explanation of the interface of the PHP SPL standard library, splinterface_PHP tutorial

WBOY
Release: 2016-07-13 09:54:29
Original
1216 people have browsed it

Detailed explanation of the interface (Interface) of the PHP SPL standard library, splinterface

The PHP SPL standard library has a total of 6 interfaces, as follows:

1.Countable
2.OuterIterator
3.RecursiveIterator
4.SeekableIterator
5.SplObserver
6.SplSubject

Among them, OuterIterator, RecursiveIterator, and SeekableIterator all inherit the Iterator class. The function and use of each interface will be explained in detail below.

Coutable interface:

Objects that implement the Countable interface can be used for counting with the count() function.
Copy code The code is as follows:
class Mycount implements Countable
{
Public function count()
{
         static $count = 0;
         $count ;
         return $count;
}
}

$count = new Mycount();
$count->count();
$count->count();

echo count($count); //3
echo count($count); //4

Description:

When calling the count() function, the Mycount::count() method is called
The second parameter of the count() function will have no effect

OuterIterator interface:

Customize or modify the iteration process.
Copy code The code is as follows:
//IteratorIterator is an implementation class of OuterIterator
class MyOuterIterator extends IteratorIterator {

Public function current()
{
           return parent::current() . 'TEST';
}
}

foreach(new MyOuterIterator(new ArrayIterator(['b','a','c'])) as $key => $value) {
echo "$key->$value".PHP_EOL;
}
/*
Result:
0->bTEST
1->aTEST
2->cTEST
*/

In practical applications, OuterIterator is extremely useful:

Copy code The code is as follows:
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'mckee');
$db->query('set names utf8');
$pdoStatement = $db->query('SELECT * FROM test1', PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($pdoStatement);
$tenRecordArray = iterator_to_array($iterator);
print_r($tenRecordArray);

RecursiveIterator interface:
For looping and iterating data in a multi-layer structure, RecursiveIterator provides two additional methods:

RecursiveIterator::getChildren Gets the child iterator of the current element
RecursiveIterator::hasChildren determines whether there is an iterator under the current element

复制代码 代码如下:
class MyRecursiveIterator implements RecursiveIterator
{
    private $_data;
    private $_position = 0;
 
    public function __construct(array $data) {
        $this->_data = $data;
    }
 
    public function valid() {
        return isset($this->_data[$this->_position]);
    }
 
    public function hasChildren() {
        return is_array($this->_data[$this->_position]);
    }
 
    public function next() {
        $this->_position ;
    }
 
    public function current() {
        return $this->_data[$this->_position];
    }
 
    public function getChildren() {
        print_r($this->_data[$this->_position]);
    }
 
    public function rewind() {
        $this->_position = 0;
    }
 
    public function key() {
        return $this->_position;
    }
}
 
$arr = array(0, 1=> array(10, 20), 2, 3 => array(1, 2));
$mri = new MyRecursiveIterator($arr);
 
foreach ($mri as $c => $v) {
    if ($mri->hasChildren()) {
        echo "$c has children: " .PHP_EOL;
        $mri->getChildren();
    } else {
        echo "$v" .PHP_EOL;
    }
 
}
/*
结果:
0
1 has children:
Array
(
    [0] => 10
    [1] => 20
)
2
3 has children:
Array
(
    [0] => 1
    [1] => 2
)
*/

SeekableIterator接口:

Implement a searchable iterator through the seek() method, which is used to search for elements at a certain position.
Copy code The code is as follows:
class MySeekableIterator implements SeekableIterator {

private $position = 0;

private $array = array(
"first element" ,
"second element" ,
"third element" ,
"fourth element"
);

Public function seek ( $position ) {
If (!isset( $this -> array [ $position ])) {
                throw new OutOfBoundsException ( "invalid seek position ( $position )" );
}

$this -> position = $position ;
}

Public function rewind () {
$this -> position = 0 ;
}

Public function current () {
Return $this -> array [ $this -> position ];
}

Public function key () {
           return $this -> position ;
}

Public function next () {
$this -> position ;
}

Public function valid () {
           return isset( $this -> array [ $this -> position ]);
}
}

try {

$it = new MySeekableIterator ;
echo $it -> current (), "n" ;

$it -> seek (2);
echo $it -> current (), "n" ;

$it -> seek (1);
echo $it -> current (), "n" ;

$it -> seek (10);

} catch (OutOfBoundsException $e) {
echo $e -> getMessage ();
}
/*
Result:
first element
third element
second element
invalid seek position ( 10 )
*/

SplObserver and SplSubject interface:
The SplObserver and SplSubject interfaces are used to implement the observer design pattern. The observer design pattern means that when the state of a class changes, objects that rely on it will be notified and updated. The usage scenarios are very wide. For example, when an event occurs, multiple logical operations need to be updated. The traditional way is to write the logic after the event is added. This kind of code is coupled and difficult to maintain. The observer pattern can implement a low-coupling notification and update mechanism. .
Take a look at the interface structure of SplObserver and SplSubject:
Copy code The code is as follows:
//SplSubject structure observed object
interface SplSubject{
Public function attach(SplObserver $observer); //Add observer
Public function detach(SplObserver $observer); //Delete observer
Public function notify(); //Notify observers
}

//SplObserver structure represents the observer
interface SplObserver{
Public function update(SplSubject $subject); //Update operation
}

Look at the following example of implementing an observer:

复制代码 代码如下:
class Subject implements SplSubject
{
    private $observers = array();
 
    public function attach(SplObserver  $observer)
    {
        $this->observers[] = $observer;
    }
 
    public function detach(SplObserver  $observer)
    {
        if($index = array_search($observer, $this->observers, true)) {
            unset($this->observers[$index]);
        }
    }
 
    public function notify()
    {
        foreach($this->observers as $observer) {
            $observer->update($this);
        }
    }
 
 
}
 
class Observer1 implements  SplObserver
{
    public function update(SplSubject  $subject)
    {
        echo "逻辑1代码".PHP_EOL;
    }
}
 
class Observer2 implements  SplObserver
{
    public function update(SplSubject  $subject)
    {
        echo "逻辑2代码".PHP_EOL;
    }
}
 
 
$subject = new Subject();
$subject->attach(new Observer1());
$subject->attach(new Observer2());
 
$subject->notify();
/*
结果:
逻辑1代码
逻辑2代码
*/

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/997905.htmlTechArticlePHP SPL标准库之接口(Interface)详解,splinterface PHP SPL标准库总共有6个接口,如下: 1.Countable 2.OuterIterator 3.RecursiveIterator 4.SeekableIterator 5.SplOb...
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template