之前柚子也曾提到Slim中的集合类Collection,但因太过“短小”而被同事诟病,今天给出更为详细的关于Slim集合类的博文。该集合类也算是在Slim系列正式接触SPL的第一篇。
Slim中定义了一个集合类Collection,该类提供了对集合对象的通用接口方法。该集合类实现集合的数据结构,集合类实现的集合接口继承了ArrayAccess,Countable, IteratorAggregate几个SPL(PHP标准库)定义的接口。
下面给出了该接口在Slim中的具体实现。Slim中定义了一个集合类Collection,该类提供了对集合对象的通用接口方法。其中该类继承的CollectionInterface接口,就继承了ArrayAccess预定义接口。
/**
* 集合接口,在容器的设置中传入一个数组,返回一个Collection对象。
* Collection InterfaceCollectionInterface
* * @package Slim
* @since 3.0.0
*/
interface CollectionInterface extends \ArrayAccess, \Countable, \IteratorAggregate{
public function set($key, $value);
public function get($key, $default = null);
public function replace(array $items);
public function all();
public function has($key);
public function remove($key);
public function clear();
}
SPL简介
SPL是用于解决典型问题的一组接口与类的集合。
ArrayAccess接口
ArrayAccess是十分重要的SPL,它的作用是使你的对象可以像数组一样被访问。
接口简介,使用ArrayAccess方法需要定义四个方法。
ArrayAccess {
/* Methods */
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 )
}
Countable接口
类实现 Countable 可被用于 count() 函数.
Countable {
/* 方法 */
abstract public int count ( void )
}
IteratorAggregate接口
在了解IteratorAggregate之前,我们先了解Traversable(遍历)接口
Traversable简介
检测一个类是否可以使用 foreach 进行遍历的接口。
无法被单独实现的基本抽象接口。相反它必须由 IteratorAggregate 或 Iterator 接口实现。
IteratorAggregate(聚合式迭代器)接口
创建外部迭代器的接口。
IteratorAggregate extends Traversable {
/* 方法 */
abstract public Traversable getIterator ( void )
}
示例:
class myData implements IteratorAggregate {
public $property1 = "Public property one";
public $property2 = "Public property two";
public $property3 = "Public property three";
public function __construct() {
$this->property4 = "last property";
}
public function getIterator() {
return new ArrayIterator($this);
}
}
$obj = new myData;
foreach($obj as $key => $value) {
var_dump($key, $value);
echo "\n";
}
示例结果:
string(9) "property1”
string(19) "Public property one”
string(9) "property2”
string(19) "Public property two”
string(9) "property3”
string(21) "Public property three”
string(9) "property4" string(13) "last property"