Single-piece mode is the singleton pattern (which is the creation design pattern), the most suitable example is the log record.
Other patterns of PHP code later written in the share to everyone, I hope you can add points to the concept of design patterns in PHP. Copy Content to Clipboard
Code:
<?php
/*
* 1.Singleton pattern for the log of application
* 2. It is recommended that the class filename be written class.log.php
* so that __autoload () automatically loads the class
* 3.author:noangels
* 4.e-mail:flare_1023@163.com qq:82535599
*/
Final class log{
#构造函数, the log file is created if it is not present, and the file is opened for subsequent use
Private Function __construct () {
if (! $this->__fp = @fopen (' Application.log ', ' ab+ ')) {
$this->__errmsg = ' failed to create or read log file ';
$this->__errorhandler ();
}
}
#析构函数, releasing resources
function __destruct () {
#站位先
}
#静态函数, implement singleton design pattern with static variable
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 = ' Write to log file failed ';
$this->__errorhandler ();
}
Return
}
#将日志内容输出, the default parameter is 1, which is to print the log by default in the class internal method, otherwise you can customize the display. The array is returned in two cases
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 ' record time: '. Date (' y-m-d h:m:s ', $temp [0]). ' <br/> reason: '. $temp [1]. ' <br/> ';
}
}
#私有变量, initialize each variable
static private $__instance = NULL;
Private $__FP = NULL;
Private $__errmsg = ';
}
?>
attached test documents
Code:
<?php
try{
if(!@mysqli_connect('localhost', 'root', '10d237776')){
throw new Exception('mysql connect failed!');
}
}
catch(Exception $e){
print 'y';
log::getInstance()->inLog($e->getMessage());
}
?>