打印

[php] 发个单件模式的简单例子

单件模式即singleton pattern(属于创建型设计模式),最适合解释的例子就是日志记录了.
其他模式的php代码以后写好了在分享给大家,希望可以增加点大家对php中设计模式的概念.
复制内容到剪贴板
代码:
<?php
/*
* 1.Singleton Pattern for the log of application
* 2.建议将类文件名写成class.log.php
* 以便__autoload()自动载入该类
* 3.Author:NoAngels
* 4.E-mail:flare_1023@163.com QQ:82535599
*/
final class log{
    #构造函数,日志文件不存在就创建否则就打开文件以供后续使用
    private function __construct(){
        if(!$this->__fp = @fopen('application.log', 'ab+')){
            $this->__errMsg = '创建或读取日志文件失败';
            $this->__errorHandler();
        }
    }
    #析构函数,释放资源
    function __destruct(){
        #站位先
    }
    #静态函数,配合静态变量使用,实现singleton设计模式
    static function getInstance(){
        if(self::$__instance == NULL){
            self::$__instance = new log;
        }
        return self::$__instance;
    }    
    #类内部错误处理机制
    private function __errorHandler(){
        die($this->__errMsg);
    }
    #将指定内容写入到日志文件中
    public function inLog($temp){
        if(@fwrite($this->__fp, time()."|||".$temp."\r\n") === FALSE){
            $this->__errMsg = '写入到日志文件失败';
            $this->__errorHandler();
        }
        return;
    }
    #将日志内容输出,参数默认为1,即默认用类内部方法打印日志,否则可自定义显示方式.两种情况下都返回数组
    public function outLog($default = 1){
        $outArray = array();
        while(!feof($this->__fp)){
            $line = fgets($this->__fp);
            if(strlen($line) != 0){
                $tmp = explode("|||", $line, 2);
                $outArray[] = $tmp;
            }            
        }
        if($default == 1){
            $this->__printLog($outArray);        
        }
        return $outArray;            
    }
    #默认日志输出方式
    private function __printLog($arr){
        foreach($arr as $temp){
            echo '记录时间:'.date('Y-m-d H:m:s' , $temp[0]).'<br/>原因:'.$temp[1].'<br/>';
        }        
    }
    #私有变量,初始化每个变量
    static private $__instance = NULL;
    private $__fp = NULL;
    private $__errMsg = '';
}
?>
附上测试文件
复制内容到剪贴板
代码:
<?php
try{
    if(!@mysqli_connect('localhost', 'root', '10d237776')){
        throw new Exception('mysql connect failed!');
    }
}
catch(Exception $e){
    print 'y';
    log::getInstance()->inLog($e->getMessage());
}
?>
帮楼主顶一下.

期待楼主继续发贴. 如果能有详细的文字说明就好了.
求二手电视、热水器、冰箱
论坛前段时间出问题,弄的我这边一直上不去,晚些时候整理一下继续发帖,希望大家关注
写得蛮规范的嘛,null建议小写.@建议少用,很耗资源,直接error_reporting(0)就行了.

TOP

还在为头像烦恼?还在为不能关注好友动态烦忧?快来蓝色理想家园吧!