PHP SPL Standard library Interface (Interface) Learn notes

Source: Internet
Author: User
Tags abstract foreach arrays data structures spl rewind


Brief introduction

SPL is all called (Standard PHP library,php Standard library), from the official document, SPL mainly contains the following blocks:
Interface
Data
Iterators
Abnormal
function enhancement
Arrayobject
Sqlfileinfo

One, interface

Interfaces provide constraints on classes, and in a well-formed class library there are usually very well designed interface definitions, which include abstractions that are abstract to interfaces and avoid misuse of interfaces. In SPL, the main interface has the following: countable,
Outeriterator,recursiveiterator,seekableiterator.

First of all, these methods are inherited from iterator, review the definition of iterator:

1:iterator extends Traversable {
2:
3:abstract Public mixed current (void)
4:abstract Public scalar key (void)
5:abstract public void Next (void)
6:abstract public void Rewind (void)
7:abstract public boolean valid (void)
8:}

Countable is clearly providing a counting convention, on top of iterator, to get the number of the collection from the Count method.
Outiterator encapsulates the iterator, adding a way to get the iterator.
Recursiceiterator supports iterations based on iterator, new methods for checking and acquiring child nodes.
Seekiterator based on iterator, a seek method is added to get the object at the specified location.

Third, data structure

SPL configures PHP with some enhanced data structures that make PHP look a little more modern. The following data structures are added:
Double linked list
Stack
Queue
Priority queues
Heap
Big Top Pile
Small Top heap
Array
Fixed-length arrays
Mapping
Object Mappings

Double-linked lists (spldoublylinkedlist), Stacks (Splstack), Queues (Splqueue), priority queues (Splpriorityqueue) all implement iterator interfaces, arrayaccess interfaces, Countable interface.  We mainly review the next arrayaccess, we used the array, can be seen as a map of the version, and Arrayaccess, is the map version, that is, you can use this method to access objects: arr["one"]=1;  arr[obj1]=2; Continue to look at the data structure, double linked list and so on above the interface on the basis of increased pop,push and other common operation of this interface.
The heap (splheap), the large Top heap (splmaxheap), and the small top heap (splminheap) inherit only the iterator interface and the countable interface. It is worth mentioning that the big top heap and the small top heap are the Compare method to insert data into the heap, the structure of the heap to maintain the screen operation.
Fixed-length arrays (splfixedarray), regular arrays support a variety of data types of keys, and the length of variable, flexible and also bring performance loss. Fixed-length arrays sacrifice flexibility in exchange for performance. The specific performance of the assessment can be seen here.

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

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.

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:

$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

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.

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:

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:

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.