通过ArrayAccess接口,我们可以用数组形式访问对象。这种场景适用于数组操作,同时也需要定义数据的某些方法(例如保存数据)。
实现这个类,必须实现ArrayAccess的4个接口:
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 )
}
注意:不要把这个对象传递给smarty,否则会导致数据无法获取,应该先转换为数组。
namespace Client;
/**
* @author 志斌
* @date 2017年4月5日
*/
class Storage implements \ArrayAccess
{
/**
* 微端数据cookie名称
* @var string
*/
const COOKIE_NAME = 'xxxx';
/**
* 存储storage的数据
* @var array
*/
private $data = [];
/**
* 构造函数
* @return void
*/
public function __construct()
{
$cookie = isset($_COOKIE[self::COOKIE_NAME]) ? $_COOKIE[self::COOKIE_NAME] : '';
$storage = unserialize(urldecode($cookie));
$this->data = is_array($storage) ? $storage : [];
}
/**
* 清空storage中的数据
* @return void
*/
public function clearAll()
{
$this->data = [];
}
/**
* 以数组的形式返回数据
* @return array:
*/
public function toArray()
{
return $this->data;
}
/**
* 保存storage到cookie中
* @return void
*/
public function saveStorage()
{
setcookie(self::COOKIE_NAME, urlencode(serialize($this->data)), null, "/", "37.com");
}
/**
* 判断key是否存在
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->data[$offset]);
}
/**
* 取得key对应的值
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
return $this->offsetExists($offset) ? $this->data[$offset] : null;
}
/**
* 设置key对应的值
* @param mixed $offset
* @param mixed $value
* @return void
*/
public function offsetSet($offset, $value)
{
if (is_null($offset)) {
$this->data[] = $value;
} else {
$this->data[$offset] = $value;
}
}
/**
* 删除key对应的值
* @param mixed $offset
* @return void
*/
public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
}