PHP SPL Standard library Interface (Interface) detailed

Source: Internet
Author: User
Tags foreach spl rewind

This article mainly introduced the PHP SPL standard library Interface (Interface) detailed explanation, this article explained separately coutable interface, the Outeriterator interface, the Recursiveiterator interface, the Seekableiterator interface, Splobserver and Splsubject interface and other content, need friends can refer to the following

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

Where Outeriterator, Recursiveiterator, and Seekableiterator are inherited from the iterator class, the following describes each interface's role and use in detail.

Coutable Interface:

Objects that implement the countable interface can be used for count () function counts.

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 the count () function is invoked, the Mycount::count () method is called

The second parameter of the count () function will not have an effect

Outeriterator Interface:

Customize or modify the iteration process.

The code is as follows:

Iteratoriterator is an implementation class for Outeriterator

Class Myouteriterator extends Iteratoriterator {

Public Function current ()

{

Return Parent::current (). ' TEST ';

}

}

foreach (New Myouteriterator arrayiterator ([' B ', ' A ', ' C ']) as $key => $value) {

echo "$key-> $value". Php_eol;

}

/*

Results:

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:

For iterating over multiple layers of data, Recursiveiterator provides two additional methods:

Recursiveiterator::getchildren gets the current element-the iterator

Recursiveiterator::haschildren to determine if 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 (a), 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;

}

}

/*

Results:

0

1 has children:

Array

(

[0] => 10

[1] => 20

)

2

3 has children:

Array

(

[0] => 1

[1] => 2

)

*/

Seekableiterator Interface:

A searchable iterator is implemented through the Seek () method to search for elements under a location.

The code is as follows:

Class Myseekableiterator implements Seekableiterator {

Private $position = 0;

Private $array = Array (

"A",

"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 ();

}

/*

Results:

A-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 pattern, which means that when a class's state changes, objects that depend on it are notified and updated. The use of scenarios is very broad, for example, when an event occurs, the need to update multiple logical operations, the traditional way is to write logic after the event is added, this code coupling and difficult to maintain, observer mode can achieve low coupling notification and update mechanism.

Look at the interface structure of Splobserver and Splsubject:

The code is as follows:

Splsubject structure of observed objects

Interface splsubject{

Public function Attach (Splobserver $observer); Add Observer

Public Function Detach (Splobserver $observer); Culling The Observer

Public function notify (); INFORM the Observer

}

SPLOBSERVER structure represents the Observer

Interface splobserver{

Public Function Update (Splsubject $subject); Update action

}

Look at one of the following examples of implementing an observer:

Copy code code 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->notify ();

/*

Results:

Logical 1 Code

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