单件模式属于构造型模式,特别适合于向log记录等等应用,特点是只存在一个该类的实例. 方法:在类中定义一个一个静态变量来引用该类的实例以及一个静态方法,返回实例. 具体请看代码:实例比较简单,是为了让大家对单件模式有个理解,其他模式相关代码以后放出.
<?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());
}
?>