slim中的依赖注入基于pimple,于是又去学习了一下pimple。 对比之前自己写的依赖注入类,pimple有一个很新鲜的用法,不是采用
$container->session_storage = function ($c) {
return new $c['session_storage_class']($c['cookie_name']);
};
而是以数组方式进行注入:
$container['session_storage'] = function ($c) {
return new $c['session_storage_class']($c['cookie_name']);
};
看源码时才发现原来诀窍就在php5提供的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 ) #删除数据
如果想让对象使用起来像一个 php 数组,那么我们需要实现 arrayaccess 接口
代码如下:
interface arrayaccess
boolean offsetexists($index)
mixed offsetget($index)
void offsetset($index, $newvalue)
void offsetunset($index)
下面的例子展示了如何使用这个接口,例子并不是完整的,但是足够看懂,:->
代码如下:
<?php
class usertosocialsecurity implements arrayaccess
{
private $db;//一个包含着数据库访问方法的对象
function offsetexists($name)
{
return
$this->db->userexists($name);
}
function offsetget($name)
{
return $this->db->getuserid($name);
}
function offsetset($name, $id)
{
$this->db->setuserid($name, $id);
}
function offsetunset($name)
{
$this->db->removeuser($name);
}
}
$usermap = new usertosocialsecurity();
print "john's id number is " . $usermap['john'];
?>
实际上,当 $usermap['john'] 查找被执行时,php 调用了 offsetget() 方法,由这个方法再来调用数据库相关的 getuserid() 方法。
以上就是代码详解php中的arrayaccess接口的详细内容。