一个简单的xml读写类理解下面向对象(二)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/youcijibi/article/details/87905402

比较上段代码引入了异常处理。

try{}catch(){}时特殊的处理放在前面,因为捕捉后会停止继续捕获,所以特殊自定义的放前面才能获取到更详细的所需要的异常信息。而不是系统默认的简单异常信息。

<?php
class XmlException extends Exception
{
    private $_error;

    public function __construct(LibXMLError $error)
    {
        $msg = 'file:' . $error->file . 'line:' . $error->line . 'column:' . $error->column . 'message:' . $error->message;
        $this->_error = $error;
        parent::__construct($msg, $error->code); //调用父类方法传入message及code参数,因为此类继承父类所以子类中使用getmessage及getcode方法时得到的值就是此时传入的
    }

    public function getError()
    {
        return $this->_error;
    }
}

class FileException extends Exception
{}

class ConfException extends Exception
{}

class Conf
{
    private $_file;
    private $_xml;
    private $_lastMatch;

    public function __construct($file)
    {
        if (!file_exists($file)) {
            throw new FileException('file:' . $file . 'not exists');
        }

        $this->_file = $file;
        $this->_xml = simplexml_load_file($file);

        if (!is_object($this->_xml)) {
            throw new XmlException(libxml_get_last_error());
        }
        gettype($this->_xml);
        $matches = $this->_xml->xpath('/conf');
        if (!count($matches)) {
            throw new ConfException('element conf is not exists');
        }
    }
   
    //此处加入对文件的可写性判断,不能写入时抛出异常,看官自行处理

    public function Write() 
    {
        file_put_contents($this->_file, $this->_xml->asXML());
    }

    public function Get($str)
    {
        $matches = $this->_xml->xpath("/conf/item[@name=\"$str\"]");
        if (count($matches)) {
            $this->_lastMatch = $matches[0]; //对象的引用传递,只有经过这一步才会使下面的(set)值生效,如果这里赋值为$matches则不行,因为它是个数组不是对象
            return  $matches;
        }
        return null;
    }

    public function Set($key, $value)
    {
        if (!is_null($this->Get($key))) {
            $this->_lastMatch[0] = $value; //对象的引用传递,在Get方法中$this->_lastMatch被赋值为$matches[0]这个对象,所以这里修改$this->_lastMatch中的值时$matches[0]这个对象也会被改变
            return;
        }
        $conf = $this->_xml->conf;
//        var_dump($conf);die;
        $conf->addChild('item', $value)->addAttribute('name', $key);
    }
}

try {
    $conf = new Conf(dirname(__FILE__) . '/test.xml');
} catch (FileException $e) {
    echo '文件不存在';
} catch (ConfException $e) {
    echo '元素存在问题';
} catch (XmlException $e) {
    echo $e->getMessage();
}
catch (Exception $e) {
//    echo $e->getMessage();
}

//$user = $conf->Get('user');
//var_dump( $user );
//$new_user = $conf->Set('user', 'LiLy');
//$user = $conf->Get('user');
//var_dump( $user );
//var_dump($user);
//var_dump((string)$conf);
//$conf->Set('gender1', 'boy');
//$conf->Write();

猜你喜欢

转载自blog.csdn.net/youcijibi/article/details/87905402