


Use the observer pattern to handle exception information, observer pattern_PHP tutorial
Use the observer pattern to handle exception information. The observer pattern
The capture of exception information is of great significance to programming testing. Here we combine the observer pattern to explore how to handle exception information.
Regarding the observer mode, if you haven’t come across it yet, there are many excellent bloggers in the blog garden who have explained it in detail. The author feels that the so-called observer pattern must have two important components: a subject object and multiple observers. When using it, we can plug the observer into the socket of the theme object like a plug, and use the theme object to complete the corresponding functions.
Since the observer is to be used as a plug, it must have a unified caliber to plug into the same socket, so first define an interface, Exception_Observer.php:
<?<span>php </span><span>/*</span><span>* * 定义的规范 </span><span>*/</span> <span>interface</span><span> Exception_Observer{ </span><span>public</span> <span>function</span> update(Observer_Exception <span>$e</span><span>); } </span>?>
Compared to many observers, we should first focus on the only subject object, Observer_Exception.php:
<?<span>php </span><span>class</span> Observer_exception <span>extends</span> <span>Exception</span><span>{ </span><span>public</span> <span>static</span> <span>$_observers</span>=<span>array</span><span>(); </span><span>public</span> <span>static</span> <span>function</span> attach(Exception_Observer <span>$observer</span><span>){ self</span>::<span>$_observers</span>[]=<span>$observer</span><span>; } </span><span>public</span> <span>function</span> __construct(<span>$message</span>=<span>null</span>,<span>$code</span>=0<span>){ parent</span>::__construct(<span>$message</span>,<span>$code</span><span>); </span><span>$this</span>-><span>notify(); } </span><span>public</span> <span>function</span><span> notify(){ </span><span>foreach</span> (self::<span>$_observers</span> <span>as</span> <span>$observer</span><span>) { </span><span>$observer</span>->update(<span>$this</span><span>); } } }</span>
We can clearly see that the static variable $_observers is used to place the inserted observers, and notify() is used to notify all observer objects.
Need to pay attention here $observer->update($this); inside $this Many beginners will feel that "it turns out that $this can also be used in this way".
A small question: $_observers Is it okay if it is not a static variable? We will answer this question later.
Define two observers, which in principle implement the functions defined by the interface.
Email_Exception_Observer.php:
<span>class</span> Emailing_Exception_Observer <span>implements</span><span> Exception_Observer{ </span><span>protected</span> <span>$_email</span>="huanggbxjp@sohu.com"<span>; </span><span>function</span> __construct(<span>$email</span>=<span>null</span><span>) { </span><span>if</span> (<span>$email</span>!==<span>null</span>&&filter_var(<span>$email</span>,<span>FILTER_VALIDATE_EMAIL)) { </span><span>$this</span>->_email=<span>$email</span><span>; } } </span><span>public</span> <span>function</span> update(Observer_Exception <span>$e</span><span>){ </span><span>$message</span>="时间".<span>date</span>("Y-m-d H:i:s").<span>PHP_EOL</span><span>; </span><span>$message</span>.="信息".<span>$e</span>->getMessage().<span>PHP_EOL</span><span>; </span><span>$message</span>.="追踪信息".<span>$e</span>->getTraceAsString().<span>PHP_EOL</span><span>; </span><span>$message</span>.="文件".<span>$e</span>->getFile().<span>PHP_EOL</span><span>; </span><span>$message</span>.="行号".<span>$e</span>->getLine().<span>PHP_EOL</span><span>; </span><span>error_log</span>(<span>$message</span>,1,<span>$this</span>-><span>_email); } }</span>
Logging_Exception_Observer.php:
<?<span>php </span> <span>class</span> Logging_Exception_Observer <span>implements</span><span> Exception_Observer { </span><span>protected</span> <span>$_filename</span>="F:/logException.log"<span>; </span><span>function</span> __construct(<span>$filename</span>=<span>null</span><span>) { </span><span>if</span> (<span>$filename</span>!==<span>null</span>&&<span>is_string</span>(<span>$filename</span><span>)) { </span><span>$thvis</span>->_filename=<span>$filename</span><span>; } } </span><span>public</span> <span>function</span> update(Observer_Exception <span>$e</span><span>){ </span><span>$message</span>="时间".<span>date</span>("Y-m-d H:i:s").<span>PHP_EOL</span><span>; </span><span>$message</span>.="信息".<span>$e</span>->getMessage().<span>PHP_EOL</span><span>; </span><span>$message</span>.="追踪信息".<span>$e</span>->getTraceAsString().<span>PHP_EOL</span><span>; </span><span>$message</span>.="文件".<span>$e</span>->getFile().<span>PHP_EOL</span><span>; </span><span>$message</span>.="行号".<span>$e</span>->getLine().<span>PHP_EOL</span><span>; </span><span>error_log</span>(<span>$message</span>,3,<span>$this</span>-><span>_filename); } }</span>
After designing all the main objects and plug-ins, let’s do a small test:
<?<span>php </span><span>require</span> 'Exception_Observer.php'<span>; </span><span>require</span> 'Observer_Exception.php'<span>; </span><span>require</span> 'Logging_Exception_Observer.php'<span>; </span><span>require</span> 'Emailing_Exception_Observer.php'<span>; Observer_Exception</span>::attach(<span>new</span><span> Logging_Exception_Observer()); </span><span>class</span> MyException <span>extends</span><span> Observer_Exception{ </span><span>public</span> <span>function</span><span> test(){ </span><span>echo</span> 'this is a test'<span>; } </span><span>public</span> <span>function</span><span> test1(){ </span><span>echo</span> "我是自定义的方法处理这个异常"<span>; } } </span><span>try</span><span> { </span><span>throw</span> <span>new</span> MyException("出现异常,记录一下"<span>); } </span><span>catch</span> (MyException <span>$e</span><span>) { </span><span>echo</span> <span>$e</span>-><span>getMessage(); </span><span>echo</span> "<ht/>"<span>; } </span>?>
This example first loads the observer and then performs other operations. Returning to the question raised above, can $_observers not be a static variable? The answer is no. If $_observers is not a static variable, the behavior of loading observers has no impact on subsequent operations. static allows all instance members to share a variable. Even class inheritance works just as well. If you are interested, you can continue to explore the magical effects of static.
This example shows that the output is no different from the general situation, but the difference is that the corresponding log has been generated under the customized file. Although the final function is simple, many people can even implement it in simpler ways with less code. However, when implementing more complex systems, the observer pattern brings us great convenience.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to use the event manager (EventManager) to implement the observer pattern in the Phalcon framework Introduction: The event manager (EventManager) is one of the powerful and flexible core functions in the Phalcon framework. By using event managers, you can easily implement the Observer pattern to achieve loose coupling between objects in your application. This article will introduce you to how to use the event manager in the Phalcon framework to implement the observer pattern and provide corresponding code examples. step one

Introduction PHP design patterns are a set of proven solutions to common challenges in software development. By following these patterns, developers can create elegant, robust, and maintainable code. They help developers follow SOLID principles (single responsibility, open-closed, Liskov replacement, interface isolation and dependency inversion), thereby improving code readability, maintainability and scalability. Types of Design Patterns There are many different design patterns, each with its own unique purpose and advantages. Here are some of the most commonly used PHP design patterns: Singleton pattern: Ensures that a class has only one instance and provides a way to access this instance globally. Factory Pattern: Creates an object without specifying its exact class. It allows developers to conditionally

1. What are PHP design patterns? PHP design patterns are predefined code templates designed to solve common software development problems. They provide proven solutions that improve code reusability, maintainability, and scalability. 2. Types of PHP design patterns There are many different design patterns in PHP, and each pattern has its specific purpose. The most common patterns include: Singleton Pattern: Ensures there is only one instance of a class. Factory Pattern: Creates objects of different types based on the data passed to it. Strategy mode: Allows a program to change its behavior at runtime. Observer Pattern: Allows objects to subscribe to events and be notified when events occur. 3. Singleton mode example classSingleInstance{private

Improve Java programming skills: Master the implementation of adapter mode and observer mode, need specific code examples Introduction: In daily software development, we often need to deal with compatibility issues between different classes, and also need to implement various user interfaces Event monitoring and processing. Adapter pattern and Observer pattern are two commonly used design patterns that can effectively solve these problems. This article will introduce the implementation of adapter pattern and observer pattern in detail, and provide specific Java code examples to help readers better understand. one,

Design patterns are a widely used concept in modern software development. Design patterns are common solutions found in software systems that are tested and proven to help developers build complex software applications more efficiently. The observer pattern is one of the most common design patterns, and it is also an important concept that PHP developers need to master. In this article, we will introduce the concept and implementation of the Observer pattern and demonstrate how to use it in a PHP application. What is the observer pattern? Observer pattern is a

Observer pattern in PHP and its usage examples explained Observer pattern is a software design pattern used to establish one-to-many dependencies between objects. In this mode, when the state of an object changes, all objects that depend on it are notified and automatically updated. In PHP programming, the observer pattern is a commonly used design pattern that can help us optimize and simplify the code and improve the readability and maintainability of the code. The following will introduce the basic methods of the observer pattern in PHP and explain its use with examples. The basics of the observer pattern

The observer pattern in the Java framework defines behavior through interfaces and abstract classes (1); Subject and Observer classes implement management and response behavior (2); Subject provides subscription and cancellation methods, maintains observer collections, and notifies observers (3) . In the example, Subject manages observers and triggers events (4), and ConcreteObserver responds to events (5).

In-depth analysis of the Observer pattern in PHP object-oriented programming The Observer pattern is a commonly used design pattern used to achieve loose coupling between objects in software systems. Its core idea is: an object (called an observer or subject) maintains a list of objects (called observers) that depend on it. When the state of the observed object changes, it will automatically notify all observers. . In this way, the observer pattern can implement a one-to-many relationship between objects. When an object changes, all related objects will be notified and can
