Home Backend Development PHP Tutorial 使用观察者模式处理错误信息

使用观察者模式处理错误信息

Jun 13, 2016 pm 12:23 PM
exception function message php

使用观察者模式处理异常信息

  异常信息的捕获对编程测试有着重要的意义,这里结合观察者模式,探索如何处理异常信息。

  关于观察者模式,如果还没有接触过的话,博客园有很多优秀的博友做了详细的 解释。笔者觉得,所谓观察者模式,必须有两个重要组成部分:一个主题对象,多个观察者。在使用的时候,我们可以将观察者像插头一样插到主题对象这个插座上,利用主题对象完成相应功能。

  既然观察者要作为插头,必须要有一个统一的口径才能插到相同的插座上,因而先定义一个接口,Exception_Observer.php:

<span style="color: #000000;">php </span><span style="color: #008000;">/*</span><span style="color: #008000;">* * 定义的规范  </span><span style="color: #008000;">*/</span><span style="color: #0000ff;">interface</span><span style="color: #000000;"> Exception_Observer{    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> update(Observer_Exception <span style="color: #800080;">$e</span><span style="color: #000000;">);}  </span>?>
Copy after login

  相对于众多观察者,我们首先应该关注唯一的主题对象,Observer_Exception.php:

<span style="color: #000000;">php</span><span style="color: #0000ff;">class</span> Observer_exception <span style="color: #0000ff;">extends</span> <span style="color: #0000ff;">Exception</span><span style="color: #000000;">{    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #800080;">$_observers</span>=<span style="color: #0000ff;">array</span><span style="color: #000000;">();    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">function</span> attach(Exception_Observer <span style="color: #800080;">$observer</span><span style="color: #000000;">){        self</span>::<span style="color: #800080;">$_observers</span>[]=<span style="color: #800080;">$observer</span><span style="color: #000000;">;    }     </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> __construct(<span style="color: #800080;">$message</span>=<span style="color: #0000ff;">null</span>,<span style="color: #800080;">$code</span>=0<span style="color: #000000;">){        parent</span>::__construct(<span style="color: #800080;">$message</span>,<span style="color: #800080;">$code</span><span style="color: #000000;">);        </span><span style="color: #800080;">$this</span>-><span style="color: #000000;">notify();    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> notify(){        </span><span style="color: #0000ff;">foreach</span> (self::<span style="color: #800080;">$_observers</span> <span style="color: #0000ff;">as</span> <span style="color: #800080;">$observer</span><span style="color: #000000;">) {            </span><span style="color: #800080;">$observer</span>->update(<span style="color: #800080;">$this</span><span style="color: #000000;">);        }    }}</span>
Copy after login

  我们可以清楚地看到,静态变量$_observers用来放置插入的观察者,notify()用来通知所有观察者对象。

  这里需要注意 $observer->update($this); 里面 $this 的用法,很多初学者会感到“原来 $this 也可以这么用啊”。

  一个小问题: $_observers 不是静态变量可不可以? 这个问题我们后面回答。

  定义两个观察者,原则上实现接口所定义的功能。

  Email_Exception_Observer.php:

<span style="color: #0000ff;">class</span> Emailing_Exception_Observer <span style="color: #0000ff;">implements</span><span style="color: #000000;"> Exception_Observer{    </span><span style="color: #0000ff;">protected</span> <span style="color: #800080;">$_email</span>="[email protected]"<span style="color: #000000;">;    </span><span style="color: #0000ff;">function</span> __construct(<span style="color: #800080;">$email</span>=<span style="color: #0000ff;">null</span><span style="color: #000000;">)    {        </span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$email</span>!==<span style="color: #0000ff;">null</span>&&filter_var(<span style="color: #800080;">$email</span>,<span style="color: #000000;">FILTER_VALIDATE_EMAIL)) {            </span><span style="color: #800080;">$this</span>->_email=<span style="color: #800080;">$email</span><span style="color: #000000;">;        }    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> update(Observer_Exception <span style="color: #800080;">$e</span><span style="color: #000000;">){        </span><span style="color: #800080;">$message</span>="时间".<span style="color: #008080;">date</span>("Y-m-d H:i:s").<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #800080;">$message</span>.="信息".<span style="color: #800080;">$e</span>->getMessage().<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #800080;">$message</span>.="追踪信息".<span style="color: #800080;">$e</span>->getTraceAsString().<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #800080;">$message</span>.="文件".<span style="color: #800080;">$e</span>->getFile().<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #800080;">$message</span>.="行号".<span style="color: #800080;">$e</span>->getLine().<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #008080;">error_log</span>(<span style="color: #800080;">$message</span>,1,<span style="color: #800080;">$this</span>-><span style="color: #000000;">_email);    }}</span>
Copy after login

  Logging_Exception_Observer.php:

<span style="color: #000000;">php </span><span style="color: #0000ff;">class</span> Logging_Exception_Observer <span style="color: #0000ff;">implements</span><span style="color: #000000;"> Exception_Observer{    </span><span style="color: #0000ff;">protected</span> <span style="color: #800080;">$_filename</span>="F:/logException.log"<span style="color: #000000;">;    </span><span style="color: #0000ff;">function</span> __construct(<span style="color: #800080;">$filename</span>=<span style="color: #0000ff;">null</span><span style="color: #000000;">)    {        </span><span style="color: #0000ff;">if</span> (<span style="color: #800080;">$filename</span>!==<span style="color: #0000ff;">null</span>&&<span style="color: #008080;">is_string</span>(<span style="color: #800080;">$filename</span><span style="color: #000000;">)) {            </span><span style="color: #800080;">$thvis</span>->_filename=<span style="color: #800080;">$filename</span><span style="color: #000000;">;        }    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span> update(Observer_Exception <span style="color: #800080;">$e</span><span style="color: #000000;">){        </span><span style="color: #800080;">$message</span>="时间".<span style="color: #008080;">date</span>("Y-m-d H:i:s").<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #800080;">$message</span>.="信息".<span style="color: #800080;">$e</span>->getMessage().<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #800080;">$message</span>.="追踪信息".<span style="color: #800080;">$e</span>->getTraceAsString().<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #800080;">$message</span>.="文件".<span style="color: #800080;">$e</span>->getFile().<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #800080;">$message</span>.="行号".<span style="color: #800080;">$e</span>->getLine().<span style="color: #ff00ff;">PHP_EOL</span><span style="color: #000000;">;        </span><span style="color: #008080;">error_log</span>(<span style="color: #800080;">$message</span>,3,<span style="color: #800080;">$this</span>-><span style="color: #000000;">_filename);    }}</span>
Copy after login

    设计完所有该有的主体对象和插件,我们做个小小的测试:

<span style="color: #000000;">php </span><span style="color: #0000ff;">require</span> 'Exception_Observer.php'<span style="color: #000000;">;</span><span style="color: #0000ff;">require</span> 'Observer_Exception.php'<span style="color: #000000;">;</span><span style="color: #0000ff;">require</span> 'Logging_Exception_Observer.php'<span style="color: #000000;">;</span><span style="color: #0000ff;">require</span> 'Emailing_Exception_Observer.php'<span style="color: #000000;">;Observer_Exception</span>::attach(<span style="color: #0000ff;">new</span><span style="color: #000000;"> Logging_Exception_Observer());</span><span style="color: #0000ff;">class</span> MyException <span style="color: #0000ff;">extends</span><span style="color: #000000;"> Observer_Exception{    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> test(){        </span><span style="color: #0000ff;">echo</span> 'this is  a test'<span style="color: #000000;">;    }    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">function</span><span style="color: #000000;"> test1(){        </span><span style="color: #0000ff;">echo</span> "我是自定义的方法处理这个异常"<span style="color: #000000;">;    }}</span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {    </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> MyException("出现异常,记录一下"<span style="color: #000000;">);    } </span><span style="color: #0000ff;">catch</span> (MyException <span style="color: #800080;">$e</span><span style="color: #000000;">) {    </span><span style="color: #0000ff;">echo</span> <span style="color: #800080;">$e</span>-><span style="color: #000000;">getMessage();    </span><span style="color: #0000ff;">echo</span> "<ht></ht>"<span style="color: #000000;">;    }</span>?>
Copy after login

  本实例首先先加载观察者,其后进行其他操作。回到上面提出的问题, $_observers 可以不是静态变量吗?答案是不可以。如果 $_observers 不是静态变量,加载观察者的行为对后续操作没有影响。static让所有实例成员共享某个变量。即便类继承也同样有效。有兴趣的可以继续探索下static的神奇作用吧。 

  本例显示输出与一般情况无异,但不同的是已在自定义的文件下生成了相应的日志。虽然最后实现的功能再简单不过,很多人甚至可以用更少的代码更简单的方法实现,但是,在实现更加复杂系统的情况下,观察者模式给我们带来很大方便。

 

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles