PHP SPL库
SPL,PHP 标准库(Standard PHP Library) ,此从 PHP 5.0 起内置的组件和接口,并且从 PHP5.3 已逐渐的成熟。SPL 其实在所有的 PHP5 开发环境中被内置,同时无需任何设置。
一.spl_autoload_register
更加方便的惰性加载
二.Iterator:迭代器
迭代器是比较重要的一种设计模式.普遍用于数组遍历.php的Iterator接口,预定义了以下方法:
Iterator extends Traversable { /* 方法 */ abstract public mixed current ( void ) abstract public scalar key ( void ) abstract public void next ( void ) abstract public void rewind ( void ) abstract public boolean valid ( void ) }
任何类只要实现了该接口,则该类就可以迭代:
示例代码:
class Users implements Iterator { protected $position = 0; protected $storage = array(); public function __construct() { $this->getWithData(); } public function getWithData() { $this->storage[] = array( array('id' => 1, 'name' => 'john'), array('id' => 2, 'name' => 'jake') ); } public function current() { return $this->storage[$this->position]; } public function next() { $this->position ++; } public function key() { return $this->position; } public function valid() { return isset($this->storage[$this->position]); } public function rewind() { $this->position = 0; } } $users = new Users(); foreach ($users as $key => $value) { echo $key; var_dump($value); } $users->rewind(); // 或者 while ($users->valid()) { $cur = $users->current(); $users->next(); var_dump($cur); }
SPL内置的迭代器类,可以方便的实现一些功能,比如迭代一个文件夹:
RecursiveIterator RecursiveIteratorIterator OuterIterator IteratorIterator FilterIterator RecursiveFilterIterator ParentIterator SeekableIterator LimitIterator GlobIterator CachingIterator RecursiveCachingIterator NoRewindIterator AppendIterator RecursiveIteratorIterator InfiniteIterator RegexIterator RecursiveRegexIterator EmptyIterator RecursiveTreeIterator ArrayIterator
ps:
注意区分ArrayIterator和ArrayAccess的区别;
ArrayAccess:提供像访问数组一样访问对象的能力的接口
三.ArrayAccess接口:
ArrayAccess { /* 方法 */ abstract public boolean offsetExists ( mixed $offset ) abstract public mixed offsetGet ( mixed $offset ) abstract public void offsetSet ( mixed $offset , mixed $value ) abstract public void offsetUnset ( mixed $offset ) }
示例代码(结合单例模式):
class Config implements ArrayAccess { private static $instance = null; private $configs; private function __construct() { $this->configs = array( 'db_type' => 'mysql', 'db_user' => 'root' ); } public static function getInstance() { if (is_null(self::$instance)) { self::$instance = new Config(); } return self::$instance; } public function offsetExists($offset) { return isset($this->configs[$offset]); } public function offsetGet($offset) { return $this->configs[$offset]; } public function offsetSet($offset, $value) { $this->configs[$offset] = $value; } public function offsetUnset($offset) { unset($this->configs[$offset]); } public function __toString() { return (string)var_export($this->configs, true); } private function __clone() { } } $config = Config::getInstance(); print $config['db_type']; print "\n"; $config['db_pwd'] = '1123'; print $config;
四.SplFixedArray
SplFixedArray 实例化一个固定长度的数组.SplFixedArray数组相比标准的PHP数组更接近于C语言的数组,而且由于splFixedArray没有使用散列(Hash)存储方式,因此效率更高.