SPL (PHP standard library)-----------------------personal notes

Source: Internet
Author: User
Tags autoload spl rewind

<?php ****************************************php Senior Programmer required *************************************************** ****

spl:php Standard library, Standand PHP Library A set of interfaces and classes that solve common problems



/*

Problem: Mathematical modeling/data structures to solve the problem of how data is stored

Element convenience, data how to view the issue

Unified invocation of common methods (common method, custom traversal)

Automatic loading of class definitions

*/


/*

Basic framework of SPL

Basic interface basic function of data structure

Iterator exception Other

*/



Common data structures for/*SPL

Bidirectional list stack Queue heap descending heap ascending heap priority queue fixed-length Array object container

*/






Doubly linked list

Weibo user A <--attention--Weibo user B <--attention--Weibo user C//unidirectional linked list

Note: The first node added to the list: Bottom/head

Last node added to the list: Top, also called trailer

Linked list pointer: Is the identity of the node that is currently concerned, can point to any node

Current node: the node that the linked list pointer points to

Node's composition: Node name key/offset node data value


Sqldoublylinkedlist class

Operation:

Current node operation: Rewind (first node), current (node), Next (Next node), Prev (Previous node)

Add node operation: Push,array_unshift

Delete node operation: Pop,shift

Positioning operation: Bottom,top

Specific node operations: Offsetexists,offsetget,offsetset,offsetunset


Implementation of the bidirectional linked list in SPL: Php-f sqldoublylinkedlist.php can be tested in cmd


$obj =new sqldoublylinkedlist ();

$obj->push (1); Push 1 into the linked list, which is to add the top top

$obj->push (2);

$obj->push (3);

$obj->unshift (10); The reverse pushes 10 into the linked list, which is 10 to occupy the key value 0, which is added to the bottom botton

$obj->rewind (); After calling rewind, there will be a pointer, that is, the current (the node value of the present pointer), pointing the pointer to bottom

$obj->next (); Move the pointer back one time

$obj->prev (); The pointer moves forward one time

echo "Current:". $obj->current (); Gets the value of the current node

if ($obj->current) {//Determine if the move is complete

echo "Current node valid\n";

}else{

echo "Current node invalid\n";

}

if ($obj->valid ()) {//You can use the built-in function to determine if the pointer has been moved (determine if the node is valid)

echo "valid list \ n";

}

$obj->pop (); Remove the closest node from top

$obj->shift (); Delete the node where the bottom is located


Two-way Linked list summary: Can be operated at both ends








A stack is a derivative of a doubly linked list

Disc Number 3rd |

Disc Number 5th |

Disc Number 7th |


Sqlstack class inherits from Sqldoublylinkedlist class

Operation:

Push: Press-in stack (deposit)

Pop: Exit stack (Take out)

Code implementation:

$Stack = new Sqlstack ();

$stack->push (' a '); Join A,B,C

$stack->push (' B ');

$stack->push (' C ');


Print_r ($stack);

Echo $stack->bottom;

Echo $stack->top;

echo $stack->offsetset (0, ' C '); The offset=0 of the stack is the position where top is located, Offset=1 is near the top of the node, and in the doubly linked list in the opposite!!!

Set the value of the Offset=0 key to C

$stack->rewind ();

$stack->current (); After Rewind (), the stack points to the top position, and the doubly linked list points to the bottom bottom

$stack->next (); Will point to the direction near bottom.

Traversing stacks

$stck->rewind ();

while ($stck->valid ()) {

echo $stack->key (). " = ". $stack->current ()." \ n ";

$stack->next ();

}

Delete stack data

$popobj = $stack->pop ();

echo "deleted element". $popobj;


Stack summary: Only from top operations, many functions such as Next,prev point to the opposite direction of the doubly linked list











Queue: In line with the meal, the first-come-first hit, the opposite of the stack

The Sqlqueue class also inherits from the Sqldoublylinkedlist class

Enqueue: Entering the queue

Dequeue: Exit queue


Code implementation:

$obj = new Sqlqueue ();

$obj->enqueue (' a '); Adding ABC to the queue

$obj->enqueue (' B ');

$obj->enqueue (' C ');

echo "bottom:". $obj->bottom. " \ n ";

echo "Top:" $obj->top. " \ n ";

$obj->offsetset (0, ' A '); Queue 0 for Bottom

$obj->rewind (); Inside the queue, point to bottom.

Traverse queue

while ($obj->valid ()) {

echo% $obj->key (). " = ". $obj->current ()." \ n ";

$obj->next ();

}

Delete

$delobj = $obj->dequeue ();


Queue Summary: Everything is based on first come first out principle.






/************************************************************************************************************** *************

Large summary of data structure:

Two-way linked list, stack, queue relationship:

Stack: Advanced back out

Queue: FIFO

Two-way linked list: Both ends are accessible

*************************************************************************************************************** *************/









Common iterator ********************************************************** for SPL **

Iterator concept: The process of iterating through the elements of a linked list or array in a uniform way is called iterative traversal, and this unified convenience tool is called an iterator.

Iterators in PHP are defined by the iterator interface.


Common iterator One: Arrayiterator-------------------------------------------------------------------------(used to iterate through an array)

1:freach and while statements traverse arrays through Arrayiterator

2:seek skipping certain elements

3:arrayiterator () to sort

Code implementation:

$fruits = Array (

"Apple" and "Apple value"

"Orange" = ' orange value ',

"Grape" = ' grape value ',

"Plum" = ' plum value ',

);

General traversal

foreach ($fruits as $key = = $value) {

echo $key. " : ". $value." \ n ";

}

Iterating through an array using a Arrayiterator iterator (equivalent to the detail of a normal loop)

$obj = new Arrayobject ($fruits);

$it = $obj->getiterator ();

foreach ($it as $key = = $value) {

echo Echo $key. " : ". $value." \ n ";

}

Need to call rewind () before using the while

$it->rewind ();

while ($it->valid ()) {

echo $it->key (). ":". $it->value (). " \ n ";

$it->next ();

}



Skipping certain elements for printing

$it->rewind ();

if ($it->valid ()) {

$it->seek (1); Skipping elements of Position=1

while ($it->valid ()) {

echo $it->key (). ":". $it->current (). " \ n ";

$it->next;

}

}


Sort Print

$it->ksort (); Sort by key letter

foreach ($it as $key = = $value) {

echo $key. " : ". $value." \ n ";

}

Sort using value

$it->asort ();

foreach ($it as $key = = $value) {

echo $key. " : ". $value." \ n ";

}









Common iterator Two: Appenditerator----------------------------------------------------------------------(iterate through several different iterators in sequential order)

Code implementation:

$array _a = new Arrayiterator (Array (' A ', ' B ', ' C '));

$array _b = new Arrayiterator (Array (' d ', ' e ', ' f '));

$it = new Appenditerator ();

$it->append ($array _a);

$it->append ($array _b);

foreach ($it as $key = = $value) {

echo $value. " \ n ";

}

/*a

B

C

D

E

f*/











Commonly used iterators three: Multipleiterator----------------------------------------------------------------------(combine data from multiple iterator into one overall visit Ask

Code implementation:

$idIter = new Arrayiterator (Array (' 01 ', ' 02 ', ' 03 '));

$nameIter = new Arrayiterator (Array (' Zhang San ', ' John Doe ', ' Harry '));

$ageIter = new Arrayiterator (Array (' 21 ', ' 23 ', ' 25 '));

$mit = new Multipleiterator (MULTIPLEITERATOR::MIT_KEY_ASSOC);

$mit->attachiterator ($idIter, "ID");

$mit->attachiterator ($nameIter, "NAME");

$mit->attachiterator ($ageIter, "age");

foreach ($mit as $value) {

Print_r ($value);

}


/*

Array

[Id]=>01,

[name]=> Zhang San,

[age]=>22

)

Array

[Id]=>02,

[name]=> John Doe,

[age]=>23

)

Array

[Id]=>03,

[name]=> Harry,

[age]=>25

)

*/








Common iterator Four: filesystemiterator----------------------------------------------------------------------(traversing file system)

Code implementation:

Date_default_timezone_get (' PRC ');

$it = new Filesystemiterator ('. '); . Represents the current directory

foreach ($it as $finfo) {

printf ("%s\t%s%8s\t%s\n",

Date ("Y-m-d h:i:s", $finfo->getmtime ()). " \ n ",//print out the format time of all files under the current folder

$finfo->isdir ()?<dir> ":" ",//determine if it is a directory

Number_format ($finfo->getsize ()),//format the file size, with commas per 3 bits

$finfo->getfilename ()

);

}



















Basic interface for SPL *********************************************************** *

1: Understanding the concept of 4 interfaces such as Countable/outeriterator/recursiveiterator/seekableiterator

2: Master the use of countable interface

Countable: Classes that inherit this interface can call count directly to get the number of elements

Outeriterator: If you want to do some processing on the iterator and then return, you can use this interface

Recursiveiterator: Iterations of a multilayer structure can be iterated, such as traversing a tree

Seekableiterator: Locating a specific element within a collection by the Seek method


Countable interface *****************************************************

Count (Array (' name ' = ' Peter ', ' id ' = ' 2 '))

Date_default_timezone_get (' PRC ')

$array =array (

Array (' name ' = ' Jonathon ', ' id ' = ' 2 '),

Array (' name ' = ' SEM ', ' id ' = ' 2 '),

Array (' name ' = ' Tom ', ' id ' = ' 2 ')

)

echo count ($array); 3 Number of self-arrays

echo Count ($array [1]); 2 Number of elements of the second child number



Class CountMe implements countable {

protected $_mycount=3;

Public function count () {

return $this->_mycount;

}

}

$obj = new CountMe ();

echo count ($obj); Display 1 without implements countable, plus display as 3!!!!!!!!!!


Outeriterator Interface *****************************************************

If you want to do some processing of the iterator and then return, you can use this interface

Iteratoriterator class when the implementation of the Outeriterator class, the extension can be directly inherited Iteratoriterator

Code implementation:

Date_default_timezone_get (' PRC ');

$array =[' Value1 ', ' Vlaue2 ', ' Vlaue3 ', ' Vlaue4 '];

$OUTEROBJ = new Outerimpl (new Arrayi ($array);

Forach ($outerObj as $key = $value) {

echo "+ +". $key. " -". $vale."            \ n "; $key will appear as Pre_0, $value will show up as Value1_tail

}


Class Outerimpl extends iteratoriterator{

Public function current () {//value

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

}

Public Function key () {//key

Return "Pre_". Parent::key ();

}

}





Recursiveiterator Interface ************************************************** ***

See doc for a picture, rough speaking.


Seekableiterator Interface *************************************************** **

See doc for a picture, rough speaking.















Use of SPL functions *********************************************************** *

1:

Autoload: In order to initialize the class object in PHP, it is necessary to find the definition of the class by some means. Typically, a class is defined in a separate file.

Aotuload is the way PHP finds these class files.

Class test{

Public Function __construct () {

echo "Loading Class libs/test.php\n";

}

}

<?php

Spl_autoload_extensions ('. class.php,.php '); The Test.class.php is automatically loaded, or it can be set to. php, and both can be

Set_include_path (Get_include_path (). Path_separator. "     libs/"); The position of the class is only under libs/.

Set AutoLoad to find a directory of defined class files, and multiple directories are split with _path_separator.

Spl_autoload_register (); PHP uses the autoload mechanism to find class definitions

New Test ();

?>




2:

__autoload Loading class

function __autoload ($class _name) {

echo "__autoload class:". $class _name. " \ n ";

Require_once ("libs/". $class _name. php ');

}

You can also customize a similar __autoload method

function ClassLoader ($class _name) {

echo "ClassLoader class:". $class _name. " \ n ";

Require_once ("libs/". $class _name. php ');

}

Spl_autoload_register (' ClassLoader '); This also renamed the __autoload Method and replaced the __autoload method with the

New Test ();


Note: The require_once can also be replaced with Set_include_path replacement, the code is implemented as follows:

function ClassLoader ($class _name) {

echo "ClassLoader class:". $class _name. " \ n ";

Set_include_path ("libs/");

Spl_autoload ($class _name); When we do not load the class file require or require_once, but want to load the class through the system lookup Include_path, we must explicitly call the Spl_autoload function, which is the name of the class to restart the automatic lookup of the class file

}

Spl_autoload_register (' ClassLoader ');

New Test ();


*************************************

Summary: The basic process of class loading, see the doc document diagram.

*************************************














SPL file-handling class library ********************************************************* ***

Two classes of libraries

Implementation code:

Date_default_timezone_get ("PRC");

$file = new Sqlfileinfo ("Tmp.txt");

echo "File is created at". Date ("Y-m-d h:i:s", $file->getctime ()). "     \ n "; View information about a file

echo "File is modified at". Date ("Y-m-d h:i:s", $file->getmtime ()). " \ n ";

Read the content inside

$FILEOBJ = $file->openfile ("R"); Open a file in the form of a read

while ($FILEOBJ->valid ()) {

echo $FILEOBJ->fgets (); Fget get a row of data inside a file

}

$OPENOBJ = null; Used to close an open file

$file null;


Here the file read into the way is object-oriented, than fopen and other functions to be concise, advocating the use!








*************************************************************************************************************** *

Course Summary: A brief

*************************************************************************************************************** *





?>



This article is from the "Flail Blog" blog, please be sure to keep this source http://sun231013.blog.51cto.com/8558055/1576803

SPL (PHP standard library)-----------------------personal notes

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.