PHP配置加载类的封装(PHP中使用ArrayAccess实现配置文件的加载/PHP SPL库应用)

github.com 地址:https://github.com/zhaozhiliang/designframe

应用场景:

1. 自己要写一个PHP框架,那肯定需要封装一个类来加载配置文件

2. 自己要写一个库类似支付宝SDK, PHPExcel 这样的,也有可能需要这样的类 来加载配置(视配置复杂程度,简单的肯定不需要了)

类封装,使用情况:

index.php 中调用; config.php 中定义配置类:

config.php 配置类代码如下:

namespace Imooc;


class Config implements \ArrayAccess
{
    protected $path;
    protected $configs = array();

    //$path 是目录
    public function __construct($path)
    {
        $this->path = $path;
    }

    /**
     * Whether a offset exists
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
     * @param mixed $key <p>
     * An offset to check for.
     * </p>
     * @return boolean true on success or false on failure.
     * </p>
     * <p>
     * The return value will be casted to boolean if non-boolean was returned.
     * @since 5.0.0
     */
    public function offsetExists($key)
    {
        return isset($this->configs[$key]);
    }

    /**
     * Offset to retrieve
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
     * @param mixed $key <p>
     * The offset to retrieve.
     * </p>
     * @return mixed Can return all value types.
     * @since 5.0.0
     */
    public function offsetGet($key)
    {
        if(empty($this->configs[$key]))
        {
            $file_path = $this->path.'/'.$key.'.php';
            $config = require $file_path;
            echo "include###";
            $this->configs[$key] = $config;
        }
        return $this->configs[$key];
    }

    /**
     * Offset to set
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
     * @param mixed $key <p>
     * The offset to assign the value to.
     * </p>
     * @param mixed $value <p>
     * The value to set.
     * </p>
     * @return void
     * @since 5.0.0
     */
    public function offsetSet($key, $value)
    {
        throw new \Exception("cannot write config file");
    }

    /**
     * Offset to unset
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
     * @param mixed $key <p>
     * The offset to unset.
     * </p>
     * @return void
     * @since 5.0.0
     */
    public function offsetUnset($key)
    {
        unset($this->configs[$key]);
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值