部署ArrayAccess界面,可以使得object像array那样操作。ArrayAccess界面包含四个必须部署的方法
- offsetExists($offset)
- offsetGet($offset) -> $object[$offset]
- offsetSet($offset, $value)
- offsetUnset($offset)
配置文件
// controller.php
<?php
return [
'home' => [
'decorator' => [
'DesignPattern\Decorator\Template'
]
]
];
核心类
// Config.php
<?php
namespace imooc;
class Config implements \ArrayAccess
{
protected $path;
protected $configs = array();
function __construct($path)
{
$this->path = $path;
}
/**
* Defined by ArrayAccess interface
* Return a value given it's key e.g. echo $A['title'];
* @param mixed key (string or integer)
* @return mixed value
*/
function offsetGet($offset)
{
if(empty($this->configs[$offset]))
{
$file_path = $this->path.'/'.$offset.'.php';
$config = require $file_path;
$this->configs[$offset] = $config;
}
return $this->configs[$offset];
}
/**
* Defined by ArrayAccess interface
* Set a value given it's key e.g. $A['title'] = 'foo';
* @param mixed key (string or integer)
* @param mixed value
* @return void
*/
function offsetSet($offset, $value)
{
if ( array_key_exists($offset,get_object_vars($this)) ) {
$this->{$key} = $value;
}
}
/**
* Defined by ArrayAccess interface
* Check value exists, given it's key e.g. isset($A['title'])
* @param mixed key (string or integer)
* @return boolean
*/
function offsetExists($offset)
{
return array_key_exists($offset,get_object_vars($this));
}
/**
* Defined by ArrayAccess interface
* Unset a value by it's key e.g. unset($A['title']);
* @param mixed key (string or integer)
* @return void
*/
function offsetUnset($offset)
{
if ( array_key_exists($offset,get_object_vars($this)) ) {
unset($this->{$key});
}
}
}
使用处
// index.php
$config = new imooc\Config(__DIR__.'./configs');
var_dump($config['controller']);