分享PHP操作配置文件的一组方法

实际应用时一些配置信息需要保存在配置文件而不是数据库时,使用下面的方法会非常方便

方法已经封装为类文件,可以直接引入并使用

<?php

/**
 *  
 * 使用方法: 
 * 
 * 一、引用
 *  require_once 'config.class.php';
 * 
 * 二、初始化
 *  $config = new Config('配置文件名');
 *   
 * 三、使用
 * 
 * 1、set方法
 * $config->set("key", "value"); //set后执行save才会写入配置文件生效
 * 
 * 2、get方法
 * $config->get("key");
 * 
 * 3、update方法
 * $config->update("key", "value"); //update后执行save才会写入配置文件生效
 * 
 * 4、delete方法
 * $config->delete("key"); //delete后执行save才会写入配置文件生效
 * 
 * 5、save方法
 * $config->save(); //为了避免频繁地写文件,建议执行完所有的set操作后再执行save操作
 * 
 * 6、简洁写法
 * $config->set("key", "value")->save();
 * 
 * ps:要操作的文件已经存在且为PHP文件 因为定义key vlue的形式为define($key, $value);可以方便的被其它文件引入并使用
 * 
 */
class Config {

    private $data;
    private $file;

    //构造函数
    function __construct($file) {
        $this->file = $file;
        $this->data = self::read($file);
    }

    //读取配置文件
    private function read($file) {
        if (!file_exists($file)) {
            return false;
        }
        $data = file($file);
        if (!$data) {
            return false;
        }
        return $data;
    }

    //获取指定项的值
    public function get($key) {
        $reg = "define(\"$key";
        foreach ($this->data as $k => $v) {
            if (strstr($v, $reg)) {
                return trim(explode("\"", $v)[3]);
            }
        }
    }

    //设置指定项的值 不存在指定项会新建 
    public function set($key, $value) {
        //检测有无重复
        $reg = "define(\"$key";
        foreach ($this->data as $k => $v) {
            if (strstr($v, $reg)) {
                return $this;
            }
        }
        //设置key value
        $reg = "\n\ndefine(\"$key\", \"$value\");";
        array_push($this->data, $reg);
        return $this;
    }

    //删除指定项
    public function delete($key) {
        $reg = "define(\"$key";
        $flag = false;
        foreach ($this->data as $k => $v) {
            if (strstr($v, $reg)) {
                unset(($this->data)[$k]);
                $flag = true;
                break;
            }
        }
        return $this;
    }

    //更新 只会更新已经存在的项
    public function update($key, $value) {
        $reg = "define(\"$key";
        $flag = false;
        foreach ($this->data as $k => $v) {
            if (strstr($v, $reg)) {
                $reg = "\n\ndefine(\"$key\", \"$value\");";
                ($this->data)[$k] = $reg;
                $flag = true;
                break;
            }
        }
        return $this;
    }

    //保存配置文件
    public function save() {
        file_put_contents($this->file, implode("", $this->data));
    }

}

原创文章,作者:witersen,如若转载,请注明出处:https://www.witersen.com

(0)
witersen的头像witersen
上一篇 2020年12月26日 上午12:09
下一篇 2020年12月29日 下午1:34

相关推荐

  • Centos8安装PHP

    安装好虚拟机后,可以进行PHP的安装。 一:安装Apache 1.安装Apache:执行命令yum install httpd 2.配置ServerName:执行命令vi /etc…

    2020年12月26日
    2.2K0

发表回复

登录后才能评论