Home > php教程 > php手册 > body text

php单件模式的简单例子

WBOY
Release: 2016-06-21 09:04:55
Original
1276 people have browsed it

单件模式即singleton pattern(属于创建型设计模式),最适合解释的例子就是日志记录了.
其他模式的php代码以后写好了在分享给大家,希望可以增加点大家对php中设计模式的概念.

复制内容到剪贴板

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

代码:
<?php <br/>try{<br>    if(!@mysqli_connect('localhost', 'root', '10d237776')){<br>        throw new Exception('mysql connect failed!');<br>    }<br>}<br>catch(Exception $e){<br>    print 'y';<br>    log::getInstance()->inLog($e->getMessage());<br>}<br>?>



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template