Interface in the PHPSPL standard library _ php instance

Source: Internet
Author: User
Tags rewind
This article describes the interfaces of the PHPSPL standard library. This article describes the Coutable Interface, OuterIterator Interface, RecursiveIterator Interface, SeekableIterator Interface, SplObserver Interface, and SplSubject Interface, if you need a php spl standard library, you can refer to the following six interfaces:

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

OuterIterator, RecursiveIterator, and SeekableIterator inherit the Iterator class. The following describes the functions and usage of each interface.

Coutable interface:

The Countable interface can be used to count the count () function.

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

Note:

When the count () function is called, the Mycount: count () method is called.
The second parameter of the count () function will not be affected.

OuterIterator interface:

Customize or modify the iteration process.

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 use, OuterIterator is extremely useful:

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:
The RecursiveIterator is used to iterate data in multiple layers. It provides two methods:

RecursiveIterator: getChildren get the subiterator under the current element
RecursiveIterator: hasChildren: determines whether there is an iterator under the current element.

The code is as follows:


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;
}

}
/*
Result:
0
1 has children:
Array
(
[0] => 10
[1] => 20
)
2
3 has children:
Array
(
[0] => 1
[1] => 2
)
*/

SeekableIterator interface:

You can use the seek () method to implement a searchable iterator to search for elements at a certain position.

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 interfaces:
The SplObserver and SplSubject interfaces are used to implement the Observer design mode. The Observer design mode means that when the status of a class changes, all objects dependent on it will receive notifications and update them. It is widely used. for example, when an event occurs, multiple logical operations need to be updated. the traditional method is to write the logic after the event is added. this code is coupled and difficult to maintain, the observer mode implements a low-coupling notification and update mechanism.
Let's look at the Interface Structure of SplObserver and SplSubject:

The code is as follows:


// Object observed in the SplSubject structure
Interface SplSubject {
Public function attach (SplObserver $ observer); // add an observer
Public function detach (SplObserver $ observer); // removes the observer
Public function Y (); // notifies the Observer
}

// The SplObserver structure represents the Observer
Interface SplObserver {
Public function update (SplSubject $ subject); // update operation
}

Let's look at the following example of implementing the Observer:

The code is as follows:


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 "logic 1 Code". PHP_EOL;
}
}

Class Observer2 implements SplObserver
{
Public function update (SplSubject $ subject)
{
Echo "logic 2 code". PHP_EOL;
}
}


$ Subject = new Subject ();
$ Subject-> attach (new Observer1 ());
$ Subject-> attach (new Observer2 ());

$ Subject-> publish Y ();
/*
Result:
Logic 1 code
Logic 2 code
*/

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.