异常信息的捕获对编程测试有着重要的意义,这里结合观察者模式,探索如何处理异常信息。
关于观察者模式,如果还没有接触过的话,博客园有很多优秀的博友做了详细的 解释。笔者觉得,所谓观察者模式,必须有两个重要组成部分:一个主题对象,多个观察者。在使用的时候,我们可以将观察者像插头一样插到主题对象这个插座上,利用主题对象完成相应功能。
既然观察者要作为插头,必须要有一个统一的口径才能插到相同的插座上,因而先定义一个接口,exception_observer.php:
php /** * 定义的规范 */interface exception_observer{ publicfunction update(observer_exception $e);} ?>
相对于众多观察者,我们首先应该关注唯一的主题对象,observer_exception.php:
phpclass observer_exception extendsexception{ publicstatic$_observers=array(); publicstaticfunction attach(exception_observer $observer){ self::$_observers[]=$observer; } publicfunction __construct($message=null,$code=0){ parent::__construct($message,$code); $this->notify(); } publicfunction notify(){ foreach (self::$_observersas$observer) { $observer->update($this); } }}
我们可以清楚地看到,静态变量$_observers用来放置插入的观察者,notify()用来通知所有观察者对象。
这里需要注意 $observer->update($this); 里面 $this 的用法,很多初学者会感到“原来 $this 也可以这么用啊”。
一个小问题: $_observers 不是静态变量可不可以? 这个问题我们后面回答。
定义两个观察者,原则上实现接口所定义的功能。
email_exception_observer.php:
class emailing_exception_observer implements exception_observer{ protected$_email=huanggbxjp@sohu.com; function __construct($email=null) { if ($email!==null&&filter_var($email,filter_validate_email)) { $this->_email=$email; } } publicfunction update(observer_exception $e){ $message=时间.date(y-m-d h:i:s).php_eol; $message.=信息.$e->getmessage().php_eol; $message.=追踪信息.$e->gettraceasstring().php_eol; $message.=文件.$e->getfile().php_eol; $message.=行号.$e->getline().php_eol; error_log($message,1,$this->_email); }}
logging_exception_observer.php:
php class logging_exception_observer implements exception_observer{ protected$_filename=f:/logexception.log; function __construct($filename=null) { if ($filename!==null&&is_string($filename)) { $thvis->_filename=$filename; } } publicfunction update(observer_exception $e){ $message=时间.date(y-m-d h:i:s).php_eol; $message.=信息.$e->getmessage().php_eol; $message.=追踪信息.$e->gettraceasstring().php_eol; $message.=文件.$e->getfile().php_eol; $message.=行号.$e->getline().php_eol; error_log($message,3,$this->_filename); }}
设计完所有该有的主体对象和插件,我们做个小小的测试:
php require 'exception_observer.php';require 'observer_exception.php';require 'logging_exception_observer.php';require 'emailing_exception_observer.php';observer_exception::attach(new logging_exception_observer());class myexception extends observer_exception{ publicfunction test(){ echo 'this is a test'; } publicfunction test1(){ echo 我是自定义的方法处理这个异常; }}try { thrownew myexception(出现异常,记录一下); } catch (myexception $e) { echo$e->getmessage(); echo ; }?>
本实例首先先加载观察者,其后进行其他操作。回到上面提出的问题, $_observers 可以不是静态变量吗?答案是不可以。如果 $_observers 不是静态变量,加载观察者的行为对后续操作没有影响。static让所有实例成员共享某个变量。即便类继承也同样有效。有兴趣的可以继续探索下static的神奇作用吧。
本例显示输出与一般情况无异,但不同的是已在自定义的文件下生成了相应的日志。虽然最后实现的功能再简单不过,很多人甚至可以用更少的代码更简单的方法实现,但是,在实现更加复杂系统的情况下,观察者模式给我们带来很大方便。
以上就介绍了使用观察者模式处理异常信息,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。