PHPSPL,StandardPHPlibrary Module (SPL標準庫)

來源:互聯網
上載者:User

著作權聲明:原創作品,允許轉載,轉載時請務必以超連結形式標明文章原始出版、作者資訊和本聲明。否則將追究法律責任。http://blog.csdn.net/mayongzhan - 馬永占,myz,mayongzhan

StandardPHPlibrary Module (SPL標準庫)
 
關於SPL的產生可以參考php源碼包內的ext下的spl
 
SPL分為幾大類
1. Iterators : SPL offers some advanced iterator algorithms。迭代器: SPL 提供了一些進階的迭代器運演算法則。
2. Directories and Files : SPL offers two advanced directory and file handling classes:目錄和檔案:SPL提供了兩個進階路徑和檔案處理類。
3. XML : SPL offers an advanced XML handling class:XML : SPL提供了一個進階XML處理類。
4. Array Overloading : SPL offers advanced Array overloading:數組重載 :SPL提供了進階數組重載。
5. Counting : interface Countable allows to hook into the standard array function count().計數:介面Countable 允許勾住標準數組方法count().
6. Exceptions : SPL provides a set of standard Exception classes each meant to indicate a certain problem type. 異常:SPL規定了一套標準異常類,每個類都標識了一類確定的問題。
7. Observer: SPL suggests a standard way of implementing the observer pattern.觀察者:SPL提出了實現觀察者模式的標準。
 
簡單的來說這些都是object,都是php已經封裝好的為了方便某些功能的類,相當符合物件導向...
 
一些例子:
得到SPL相關類的方法
DirectorIterator
ArrayObject
ArrayIterator
Recursive Array Iterator
PDO & IteratorIterator
FilterIterator
XML & RecursiveIteratorIterator
SimpleXMLIterator
LimitIterator & ArrayIterator
SPLFileObject
 
 
 
得到SPL相關類的方法
<?php
 foreach(get_class_methods(new DirectoryIterator('./')) as $key=>$method)
        {
        echo $key.' -> '.$method.'<br />';
        }
?>
 
DirectoryIterator
<?php
try{
  /*** class create new DirectoryIterator Object ***/
    foreach ( new DirectoryIterator('./') as $Item )
        {
        echo $Item.'<br />';
        }
    }
/*** if an exception is thrown, catch it here ***/
catch(Exception $e){
    echo 'No files Found!<br />';
}
?>
 
ArrayObject
<?php
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');

/*** create the array object ***/
$arrayObj = new ArrayObject($array);

/*** iterate over the array ***/
for($iterator = $arrayObj->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() . '<br />';
    }
?>
 
ArrayIterator
<?php
/*** a simple array ***/
$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');

try {
    /*** create a new object ***/
    $object = new ArrayIterator($array);
    /*** rewind to the beginning of the array ***/
    $object->rewind();
    /*** check for valid member ***/
    while($object->valid())
        {
        /*** echo the key and current value ***/
        echo $object->key().' -&gt; '.$object->current().'<br />';
        /*** hop to the next array member ***/
        $object->next();
        }
    }
catch (Exception $e)
    {
    echo $e->getMessage();
    }
?>
 

<?php
$array = array(
    array('name'=>'butch', 'sex'=>'m', 'breed'=>'boxer'),
    array('name'=>'fido', 'sex'=>'m', 'breed'=>'doberman'),
    array('name'=>'girly','sex'=>'f', 'breed'=>'poodle')
);

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key=>$value)
    {
    echo $key.' -- '.$value.'<br />';
    }
?>
 
PDO & IteratorIterator
<?php
// check for errors
error_reporting(E_ALL);

 try {
$dsn = new PDO("sqlite2:/home/kevin/html/periodic.sdb");

// the result only implements Traversable
$stmt = $dsn->prepare('SELECT * FROM periodic ORDER BY atomicnumber');

// exceute the query
$stmt->execute();

// the result should be an instance of PDOStatement
// IteratorIterator converts it and after that you can do any iterator operation with it
// The iterator will fetch the results for us.
$it = new IteratorIterator($stmt);

// the iterator object now has 5 arrays within.
// Each array contains a result set from the db query
foreach($it as $row)
    {
    // create the array object
    $arrayObj = new ArrayObject($row);
    // iterate over the array
    for($iterator = $arrayObj->getIterator();
    // check if valid
    $iterator->valid();
    // move to the next array member
    $iterator->next())
        {
        // output the key and current array value
        echo $iterator->current() . '<br />';
        }
    echo '<hr />';
    }
 
$dsn = null;
}
catch (PDOException $e)
    {
    print "Error!: " . $e->getMessage() . "<br />";
    }
?>
 
FilterIterator
<?php
/*** a simple array ***/
$animals = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'NZ'=>'kiwi', 'kookaburra', 'platypus');

class CullingIterator extends FilterIterator{

/*** The filteriterator takes  a iterator as param: ***/
public function __construct( Iterator $it ){
  parent::__construct( $it );
}

/*** check if key is numeric ***/
function accept(){
  return is_numeric($this->key());
}

}/*** end of class ***/
$cull = new CullingIterator(new ArrayIterator($animals));

foreach($cull as $key=>$value)
    {
    echo $key.' == '.$value.'<br />';
    }
?>
 
XML & RecursiveIteratorIterator
<?php
/*** a simple xml tree ***/
 $xmlstring = <<<XML
<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>
<document>
  <animal>
    <category id="26">
      <species>Phascolarctidae</species>
      <type>koala</type>
      <name>Bruce</name>
    </category>
  </animal>
  <animal>
    <category id="27">
      <species>macropod</species>
      <type>kangaroo</type>
      <name>Bruce</name>
    </category>
  </animal>
  <animal>
    <category id="28">
      <species>diprotodon</species>
      <type>wombat</type>
      <name>Bruce</name>
    </category>
  </animal>
  <animal>
    <category id="31">
      <species>macropod</species>
      <type>wallaby</type>
      <name>Bruce</name>
    </category>
  </animal>
  <animal>
    <category id="21">
      <species>dromaius</species>
      <type>emu</type>
      <name>Bruce</name>
    </category>
  </animal>
  <animal>
    <category id="22">
      <species>Apteryx</species>
      <type>kiwi</type>
      <name>Troy</name>
    </category>
  </animal>
  <animal>
    <category id="23">
      <species>kingfisher</species>
      <type>kookaburra</type>
      <name>Bruce</name>
    </category>
  </animal>
  <animal>
    <category id="48">
      <species>monotremes</species>
      <type>platypus</type>
      <name>Bruce</name>
    </category>
  </animal>
  <animal>
    <category id="4">
      <species>arachnid</species>
      <type>funnel web</type>
      <name>Bruce</name>
      <legs>8</legs>
    </category>
  </animal>
</document>
XML;

/*** a new simpleXML iterator object ***/
try    {
       /*** a new simple xml iterator ***/
       $it = simplexml_load_string($xmlstring, 'SimpleXMLIterator');
       /*** a new limitIterator object ***/
       foreach(new RecursiveIteratorIterator($it, 1) as $name => $data)
          {
          echo $name.' -- '.$data.'<br />';
          }
    }
catch(Exception $e)
    {
    echo $e->getMessage();
    }
?>
 
SimpleXMLIterator
<?php
$xmlstring =<<<XML
<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>
<document>
  <animal>koala</animal>
  <animal>kangaroo</animal>
  <animal>wombat</animal>
  <animal>wallaby</animal>
  <animal>emu</animal>
  <animal>kiwi</animal>
  <animal>kookaburra</animal>
  <animal>platypus</animal>
  <animal>funnel web</animal>
</document>
XML;

try {
    /*** a new simpleXML iterator object ***/
    $sxi =  new SimpleXMLIterator($xmlstring);

    /*** add an attribute with a namespace ***/
    $sxi->addAttribute('id:att1', 'good things', 'urn::test-foo');

    /*** add an attribute without a  namespace ***/
    $sxi->addAttribute('att2', 'no-ns');

    echo htmlentities($sxi->saveXML());
    }
catch(Exception $e)
    {
    echo $e->getMessage();
    }
?>
 
LimitIterator & ArrayIterator
<?php
/*** the offset value ***/
$offset = 3;

/*** the limit of records to show ***/
$limit = 2;

$array = array('koala', 'kangaroo', 'wombat', 'wallaby', 'emu', 'kiwi', 'kookaburra', 'platypus');

$it = new LimitIterator(new ArrayIterator($array), $offset, $limit);

foreach($it as $k=>$v)
    {
    echo $it->getPosition().'<br />';
    }
?>
 
 
 
SPLFileObject
<?php
try{
    // create a new spl file object from a file
        $file = new SplFileObject("./test.log");
    // check if for validity
        while($file->valid())
                {
        // echo the current line
                echo $file->current().'<br />';
        // increment the iterator
                $file->next();
                }
        }
catch (Exception $e)
        {
        echo $e->getMessage();
        }
?>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.