提供像访问数组一样访问对象的能力的接口。
接口摘要如下:
ArrayAccess {
// 获取一个偏移位置的值
abstract public mixed offsetGet ( mixed $offset )
// 设置一个偏移位置的值
abstract public void offsetSet ( mixed $offset , mixed $value )
// 检查一个偏移位置是否存在
abstract public boolean offsetExists ( mixed $offset )
// 复位一个偏移位置的值
abstract public void offsetUnset ( mixed $offset )
}
我们要实现项目配置 像数组一样去访问。
1、定义Config类 实现 ArrayAccess 接口
<?php
namespace practice\app\Logic;
class Config implements \ArrayAccess
{
protected $path;
protected $configs = array();
protected static $instance;
function __construct($path)
{
$this->path = $path;
}
static function getInstance($base_dir = '')
{
if (empty(self::$instance))
{
self::$instance = new self($base_dir);
}
return self::$instance;
}
function offsetGet($key)
{
if (empty($this->configs[$key]))
{
$file_path = $this->path.'/'.$key.'.php';
$config = require $file_path;
$this->configs[$key] = $config;
}
return $this->configs[$key];
}
function offsetSet($key, $value)
{
throw new \Exception("cannot write config file.");
}
function offsetExists($key)
{
return isset($this->configs[$key]);
}
function offsetUnset($key)
{
unset($this->configs[$key]);
}
}
2、定义配置文件如图:
项目中配置文件.png
例、database.php 配置中以数组形式返回:
<?php
return [
'master' => array(
'type' => 'MySQL',
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'root',
'dbname' => 'test',
),
'slave' => array(
'slave1' => array(
'type' => 'MySQL',
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'root',
'dbname' => 'test',
),
'slave2' => array(
'type' => 'MySQL',
'host' => '127.0.0.1',
'user' => 'root',
'password' => 'root',
'dbname' => 'test',
),
),
];
3、使用:
<?php
namespace practice;
include './autoload.php';
spl_autoload_register('autoload');
use practice\app\Logic\Config;
$key = 'slave';
$config = Config::getInstance('/configs')['database'][$key];
var_dump($config);
结果如下:
获取slave.png
如果要获取 slave 中 slave1或者 slave2 只需要:
<?php
namespace practice;
include './autoload.php';
spl_autoload_register('autoload');
use practice\app\Logic\Config;
$key = 'slave';
$key1 = 'slave2';
$config = Config::getInstance('/configs')['database'][$key][$key1];
var_dump($config);
获取slave2.png
网友评论