PHP SPL Standard library Interface (Interface) detailed, splinterface_php tutorial

Source: Internet
Author: User

PHP SPL Standard library Interface (Interface) detailed, 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

Where Outeriterator, Recursiveiterator, Seekableiterator are inherited iterator class, the following will be the role of each interface and the use of detailed description.

Coutable Interface:

Objects that implement the countable interface are available for count () function counts.
Copy the Code code 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 called, 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.
Copy the Code code 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;
}
/*
Results:
0->btest
1->atest
2->ctest
*/

In practical use, Outeriterator is extremely useful:

Copy the Code code 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:
To iterate over the data of the multilayer structure, Recursiveiterator provides two additional methods:

Recursiveiterator::getchildren gets the current element under the iterator
Recursiveiterator::haschildren determine if there is an iterator under the current element

Copy CodeThe 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, 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:

Use the Seek () method to implement a searchable iterator that searches for an element under a location.
Copy CodeThe 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 () {
+ position, $this + +;
}

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:
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 pattern, and the observer design pattern is that when the state of a class changes, the objects that depend on it are notified and updated. The use of the scene is very extensive, for example, when an event occurs, you need to update multiple logical operations, the traditional way is to write the logic after the event is added, the code is coupled and difficult to maintain, the observer pattern can implement a low-coupling notification and update mechanism.
Look at the interface structure of Splobserver and Splsubject:
Copy the Code code as follows:
Splsubject Structure-observed objects
Interface splsubject{
Public function Attach (Splobserver $observer); Add Observer
Public Function Detach (Splobserver $observer); Remove the viewer
Public function notify (); Notify the Viewer
}

SPLOBSERVER structure represents the Observer
Interface splobserver{
Public Function Update (Splsubject $subject); Update action
}

Take a look at one of the following examples of implementing observers:

Copy CodeThe 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->notify ();
/*
Results:
Logic 1 Code
Logic 2 Code
*/

http://www.bkjia.com/PHPjc/997905.html www.bkjia.com true http://www.bkjia.com/PHPjc/997905.html techarticle PHP SPL Standard library Interface (Interface) detailed, splinterface PHP SPL standard Library has a total of 6 interfaces, as follows: 1.Countable 2.OuterIterator 3.RecursiveIterator 4. Seekableiterator 5.SplOb ...

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