PHP Standard Library (SPL) notes

Source: Internet
Author: User
Tags file type file spl pop value rewind spl interface
Introduction to PHP Standard Library (SPL) notes

SPL is the abbreviation of Standard PHP Library (PHP Standard Library.

The Standard PHP Library (SPL) is a collection of interfaces and classes that are meant to solve common problems.

According to the official website, SPL is a set of interfaces and classes used to solve common problems.

So what is common problems?

-Data structure: How to store data-how to view element traversal data-unified calling of commonly used methods array and set size custom traversal-class automatic loading of spl_autoload_register

What content does it contain?

  • Data structure
  • Basic interface
  • Basic functions
  • Iterator
  • Exception
  • Others
  • SPL interface Iterator interface

    SPL stipulates that all classes that implement the Iterator interface can be used in foreach Loop. The Iterator interface contains five required methods:

    Interface Iterator extends Traversable {// return the current element public mixed current (void); // return the public scalar key (void) of the current element ); // move forward to the next element public void next (void); // return to the first element public void rewind (void) of the iterator ); // check whether the current location is valid public boolean valid (void );}

    ArrayAccess array access interface

    Implement the ArrayAccess interface to make the object operate like an array. The ArrayAccess interface contains four required methods:

    Interface ArrayAccess {// Check whether there is public mixed offsetExists (mixed $ offset) at an offset position; // obtain the value of public mixed offsetGet (mixed $ offset) at an offset position ); // set the value of one offset position to public mixed offsetSet (mixed $ offset); // reset the value of one offset position to public mixed offsetUnset (mixed $ offset );}

    IteratorAggregate aggregate iterator interface

    Assume that object A implements the preceding ArrayAccess interface. although it can be operated like an array, it cannot use foreach traversal unless it implements the Iterator interface mentioned above.

    Another solution is that you sometimes need to separate the data from the traversal part, then you can implement the IteratorAggregate interface. It specifies a getIterator () method and returns an object using the Iterator interface.

    IteratorAggregate extends Traversable {/* get an external iterator */abstract public Traversable getIterator (void )}

    Example:

     property4 = "last property";    }    public function getIterator() {        return new ArrayIterator($this);    }}$obj = new myData;foreach($obj as $key => $value) {    var_dump($key, $value);    echo "\n";}?>

    Note:
    Although they all inherit from Traversable, this is an internal engine interface that cannot be implemented in PHP scripts. We directly use the IteratorAggregate or Iterator interface instead.

    RecursiveIterator

    This interface is used to traverse multi-layer data. it inherits the Iterator interface and has standard current (), key (), next (), rewind (), and valid () methods. It also specifies the getChildren () and hasChildren () methods. The getChildren () method must return an object that implements RecursiveIterator.

    SeekableIterator

    The SeekableIterator interface is also an extension of the Iterator interface. in addition to the five methods of the Iterator, the seek () method is also specified. the parameter is the position of the element and this element is returned. If this location does not exist, OutOfBoundsException is thrown.

    Countable

    This interface specifies the number of returned result sets in a count () method.

    SPL data structure

    Data structures are used by computers to store and organize data.

    SPL provides two-way linked list, stack, queue, heap, descending heap, ascending heap, priority queue, fixed-length array, and object container.

    Basic concepts
    Bottom: node. the first node is called Bottom;
    Top: The node name of the last added linked list is Top;
    Current: The node pointed to by the linked list pointer is called the Current node;

    Spldoublyshortlist bidirectional linked list

    Spldoublyshortlist implements the Iterator, ArrayAccess, and Countable interfaces.

    Class abstract

    Spldoublyshortlist implements Iterator, ArrayAccess, Countable {/* method */public _ construct (void) public void add (mixed $ index, mixed $ newval) public mixed bottom (void) public int count (void) public mixed current (void) public int getIteratorMode (void) public bool isEmpty (void) public mixed key (void) public void next (void) public bool offsetExists (mixed $ index) public mixed offsetGet (mixed $ index) public void offsetSet (mixed $ index, mixed $ newval) public void offsetUnset (mixed $ index) public mixed pop (void) public void prev (void) public void push (mixed $ value) public void rewind (void) public string serialize (void) public void setIteratorMode (int $ mode) public mixed shift (void) public mixed top (void) public void unserialize (string $ serialized) public void unshift (mixed $ value) public bool valid (void )}

    Note:
    SplDoublyLinkedList: setIteratorMode is used to set the linked list mode:

    Iteration direction:

    SplDoublyLinkedList::IT_MODE_LIFO (Stack style)SplDoublyLinkedList::IT_MODE_FIFO (Queue style)

    Iterator behavior:

    SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

    Default Mode: spldoubly1_list: IT_MODE_FIFO | spldoubly1_list: IT_MODE_KEEP

    Current node operation:
    Rewind: points the current pointer of the linked list to the first element.
    Current: The current pointer of the linked list. when a node is deleted, it points to a null node.
    Prev: Previous
    Next: next

    Add node operation:
    Push pushes elements at the end of a two-way linked list
    Unshift pre-double-chain table elements, the pre-value starts at the beginning of the double-chain table

    Delete a node:
    Pop pops up a node from the end of the two-way linked list without changing the pointer position.
    Shift pops up a node from the beginning of a two-way linked list without changing the pointer position.

    Positioning operation:
    Bottom returns the value of the first node of the current two-way linked list. The current pointer remains unchanged.
    Top returns the value of the last node of the current two-way linked list. The current pointer remains unchanged.

    Specific node operations:
    OffsetExists indicates whether the key exists.
    OffsetGet remove the key node
    OffsetSet refresh data
    OffsetUnset deletion

    Example: spldoubly+list. php

     Push (1); // add the new node to the top $ obj-> push (2) of the linked list; $ obj-> push (3 ); $ obj-> unshift (10); // add the new node to the bottom of the linked list bottomprint_r ($ obj); $ obj-> rewind (); // The rewind operation is used to direct the node pointer to the node $ obj-> prev () where the Bottom is located; // point the pointer to the previous node and echo 'next node: 'near the Bottom :'. $ obj-> current (). PHP_EOL; $ obj-> next (); echo 'next node :'. $ obj-> current (). PHP_EOL; $ obj-> next (); if ($ obj-> current () echo 'current node valid '. PHP_EOL; else echo 'current node invalid '. PHP_EOL; $ obj-> rewind (); // if the current node is a valid node, valid returns trueif ($ obj-> valid () echo 'valid list '. PHP_EOL; else echo 'invalid list '. PHP_EOL; print_r ($ obj); echo 'pop value :'. $ obj-> pop (). PHP_EOL; print_r ($ obj); echo 'next node :'. $ obj-> current (). PHP_EOL; $ obj-> next (); // 1 $ obj-> next (); // 2 $ obj-> pop (); // delete the node at the top position from the linked list and return the result. if current refers to> to the top position, after calling pop, current () will fail to echo 'next node :'. $ obj-> current (). PHP_EOL; print_r ($ obj); $ obj-> shift (); // delete the node at the bottom position from the linked list and return print_r ($ obj );

    SplStack stack

    Stack is a special linear table, because it can only insert or delete elements at one end of the linear table (that is, the elements are pushed into and out of the Stack ).

    Stack isPost-in-first-out (LIFO).

    SplStack inherits fromBidirectional linked list spldoublyshortlist.

    Example:

     Push (1); $ stack-> push (2); $ stack-> push (3); echo 'bottom :'. $ stack-> bottom (). PHP_EOL; echo "top :". $ stack-> top (). PHP_EOL; // stack offset = 0, which is the top position (that is, the end of the stack) $ stack-> offsetSet (0, 10); echo "top :". $ stack-> top ().'
    '; // The rewind of the stack is opposite to the rewind of the two-way linked list. the rewind of the stack points the current pointer to the top position, after the two-way linked list is called, it points to the bottom location $ stack-> rewind (); echo 'Current :'. $ stack-> current ().'
    '; $ Stack-> next (); // The next operation of the stack directs the pointer to the next node near the bottom position, and the two-way linked list is the next node near the top echo 'Current: '. $ stack-> current ().'
    '; // Traverse the stack $ stack-> rewind (); while ($ stack-> valid () {echo $ stack-> key (). '=> '. $ stack-> current (). PHP_EOL; $ stack-> next (); // do not delete elements from the linked list} echo'
    '; Echo $ stack-> pop (). '--'; echo $ stack-> pop (). '--'; echo $ stack-> pop (). '--';

    Output:

    bottom:1 top:3 top:10current:10current:22=>10 1=>2 0=>1 10--2--1--
    SplQueue queue

    A queue is a typeFIFO). When a queue is used, it is inserted at one end and deleted at the other end.

    SplQueue is also inherited fromBidirectional linked list spldoublyshortlistAnd have your own methods:

    /* Method */_ construct (void) mixed dequeue (void) void enqueue (mixed $ value) void setIteratorMode (int $ mode)

    Example 1:

     enqueue(1);$queue->enqueue(2);echo $queue->dequeue() .'--';echo $queue->dequeue() .'--';//1--2--

    Example 2:

     Enqueue ('A'); $ obj-> enqueue ('B'); $ obj-> enqueue ('C'); echo 'bottom :'. $ obj-> bottom (). PHP_EOL; echo 'top :'. $ obj-> top (); echo'
    '; // The offset = 0 in the queue points to the bottom position $ obj-> offsetSet (0, 'A'); echo 'bottom :'. $ obj-> bottom (); echo'
    '; // The rewind in the queue points the pointer to the node where the bottom is located $ obj-> rewind (); echo 'Current:'. $ obj-> current (); echo'
    '; While ($ obj-> valid () {echo $ obj-> key (). '=> '. $ obj-> current (). PHP_EOL; $ obj-> next (); //} echo'
    '; // The dequeue operation extracts the bottom node from the queue, returns the node, and deletes the element echo 'dequeue obj:' from the queue :'. $ obj-> dequeue (); echo'
    '; Echo 'bottom:'. $ obj-> bottom (). PHP_EOL;

    Output:

    bottom:a top:cbottom:Acurrent:A0=>A 1=>b 2=>c dequeue obj:Abottom:b
    SplHeap heap

    Heap)It is a data structure designed to implement priority queues. it is implemented by constructing a binary heap (a binary tree.

    The largest heap of the root node isMax heapOr a large root heap. the smallest heap of the root node is calledMinimum heapOr a small root heap. Binary heap is also commonly used for sorting (heap sorting ).

    SplHeap is an abstract class that implements the Iterator and Countable interfaces. The maximum heap and the minimum heap are inherited. There is no additional method for the max heap and min heap.

    To use the SplHeap class, you need to implement its abstract method int compare (mixed $ value1, mixed $ value2 ).

    Class abstract:

    Abstract SplHeap implements Iterator, Countable {/* method */public _ construct (void) abstract protected int compare (mixed $ value1, mixed $ value2) public int count (void) public mixed current (void) public mixed extract (void) public void insert (mixed $ value) public bool isEmpty (void) public mixed key (void) public void next (void) public void recoverFromCorruption (void) public void rewind (void) public mixed top (void) public bool valid (void )}

    Example:

     Insert (4); $ obj-> insert (8); $ obj-> insert (1); $ obj-> insert (0 ); echo $ obj-> top (); // 8 echo $ obj-> count (); // 4 echo'
    '; Foreach ($ obj as $ number) {echo $ number. PHP_EOL ;}

    Output:

    848 4 1 0
    Max SplMaxHeap heap

    The max heap inherits from the abstract class SplHeap. There is no additional method for the max heap.

    SplMinHeap minimum heap

    The minimal heap inherits from the abstract class SplHeap. There is no additional method for the minimum heap.

    The minimum heap is as follows (the priority of any node is not smaller than its subnode)

    Example:

     Insert (4); $ obj-> insert (8); // extract echo $ obj-> extract (). PHP_EOL; echo $ obj-> extract (); // 4 8

    SplPriorityQueue priority queue

    The priority queue SplPriorityQueue is implemented based on the heap. Like the heap, the int compare (mixed $ priority1, mixed $ priority2) method is also available.

    SplPriorityQueue implements the Iterator and Countable interfaces.

    Example:

    $ Pq = new SplPriorityQueue (); $ pq-> insert ('A', 10); $ pq-> insert ('B', 1 ); $ pq-> insert ('C', 8); echo $ pq-> count (). PHP_EOL; // 3 echo $ pq-> current (). PHP_EOL; // a/*** sets the element queuing mode * SplPriorityQueue: EXTR_DATA only extracts the value * SplPriorityQueue: EXTR_PRIORITY only extracts the priority * SplPriorityQueue :: EXTR_BOTH extract array containing value and priority */$ pq-> setExtractFlags (SplPriorityQueue: EXTR_DATA); while ($ pq-> valid ()) {print_r ($ pq-> current (); // a c B $ pq-> next ();}

    SplFixedArray fixed length array

    SplFixedArray implements the Iterator, ArrayAccess, and Countable interfaces.

    Unlike an ordinary array, the fixed length array specifies the length of the array. The advantage is faster processing than normal arrays.

      1 [1] => 2 [2] => 3 [3] => [4] => )

    SplObjectStorage object container

    SplObjectStorage is used to store a group of objects, especially when you need to uniquely identify objects. This class implements the Countable, Iterator, Serializable, and ArrayAccess interfaces. Supports statistics, iteration, serialization, array access, and other functions.

    Example:

    Class A {public $ I; public function _ construct ($ I) {$ this-> I = $ I ;}$ a1 = new A (1 ); $ a2 = new A (2); $ a3 = new A (3); $ a4 = new A (4); $ container = new SplObjectStorage (); // SplObjectStorage :: attach add objects to Storage $ container-> attach ($ a1); $ container-> attach ($ a2); $ container-> attach ($ a3); // SplObjectStorage:: detach remove $ container-> detach ($ a2) from Storage; // SplObjectStorage :: contains is used to check whether the object has var_dump ($ container-> contains ($ a1) in Storage; // truevar_dump ($ container-> contains ($ a4 )); // false // traverse $ container-> rewind (); while ($ container-> valid () {var_dump ($ container-> current ()); $ container-> next ();}

    SPL class SPL built-in class

    In addition to defining a series of Interfaces, SPL also provides a series of built-in classes that correspond to different tasks, greatly simplifying programming.
    To view all the built-in classes, you can use the following code:

     $value)        {        echo $key.' -> '.$value.'
    '; }?>

    SplFileInfo

    Php spl provides SplFileInfo and SplFileObject classes to process file operations.

    SplFileInfo is used to obtain file details:

    $ File = new SplFileInfo('foo-bar.txt '); print_r (array ('getatime' => $ file-> getATime (), // The Last access time is 'getbasename' => $ file-> getBasename (), // Obtain the pathless basename 'getctime' => $ file-> getCTime (), // Get the inode modification time 'getextension' => $ file-> getExtension (), // file extension 'getfilename' => $ file-> getFilename (), // get the file name 'getgroup' => $ file-> getGroup (), // get the file group 'getinode' => $ file-> getInode (), // Obtain the file inode 'getlinktarget' => $ file-> getLinkTarget (), // Obtain the target file 'getmtime' => $ file-> getMTime (), // Obtain the last modification time 'getowner' => $ file-> getOwner (), // The object owner 'getpath' => $ file-> getPath (), // The path 'getpathinfo' => $ file-> getPathInfo (), // 'getpathname' => $ file-> getPathname (), // full path 'getperms' => $ file-> getPerms (), // file permission 'getrealpath' => $ file-> getRealPath (), // absolute file path 'getsize' => $ file-> getSize (), // file size, unit byte 'gettype' => $ file-> getType (), // file type file dir link 'isdir' => $ file-> isDir (), // whether the directory is 'isfile' => $ file-> isFile (), // whether the file is 'islink' => $ file-> isLink (), // whether the shortcut is 'isexecutable' => $ file-> isExecutable (), // whether 'isreadable' => $ file-> isReadable (), // whether to read 'iswritable' => $ file-> isWritable (), // whether it can be written ));

    SplFileObject

    SplFileObject inherits SplFileInfo and implements the RecursiveIterator and SeekableIterator interfaces for file traversal, search, and Operation traversal:

    try {    foreach(new SplFileObject('foo-bar.txt') as $line) {        echo $line;    }} catch (Exception $e) {    echo $e->getMessage();}

    Find the specified row:

    try {    $file = new SplFileObject('foo-bar.txt');    $file->seek(2);    echo $file->current();} catch (Exception $e) {    echo $e->getMessage();}

    Write a csv file:

    $list  = array (    array( 'aaa' ,  'bbb' ,  'ccc' ,  'dddd' ),    array( '123' ,  '456' ,  '7891' )); $file  = new  SplFileObject ( 'file.csv' ,  'w' ); foreach ( $list  as  $fields ) {    $file -> fputcsv ( $fields );}
    DirectoryIterator

    This class inherits from SplFileInfo and implements the SeekableIterator interface.

    This class is used to view all files and subdirectories in a directory:

     ';        }    }/*** if an exception is thrown, catch it here ***/catch(Exception $e){    echo 'No files Found!
    ';}?>
    ArrayObject

    This class implements the ArrayAccess, Countable, IteratorAggregate, and Serializable interfaces.

    This class can convert Array to object.

     getIterator();   /*** check if valid ***/   $iterator->valid();   /*** move to the next array member ***/   $iterator->next())    {    /*** output the key and current array value ***/    echo $iterator->key() . ' => ' . $iterator->current() . '
    '; }?>

    ArrayIterator

    This class implements the ArrayAccess, Countable, SeekableIterator, and Serializable interfaces.

    This class is actually a supplement to the ArrayObject class, providing the Traversal function for the latter.

     $value)        {        echo $key.' => '.$value.'
    '; } }catch (Exception $e) { echo $e->getMessage(); }?>

    Reference
    1. PHP: SPL-Manual
    Http://php.net/manual/zh/book.spl.php
    2. PHP: pre-defined interface-Manual
    Http://php.net/manual/zh/reserved.interfaces.php
    3. php spl notes-Ruan Yifeng's network logs
    Http://www.ruanyifeng.com/blog/2008/07/php_spl_notes.html
    4. file operations (SplFileInfo and SplFileObject) in the php spl standard library-PHP point-to-point
    Http://www.phpddt.com/php/SplFileObject.html

    Related Article

    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.