search
HomeBackend DevelopmentPHP TutorialPHP design pattern——Observer pattern

Observer Pattern

Observer pattern (Observer), when the state of an object changes, all objects that rely on it will receive notifications and automatically update.

The role in the pattern

  • Abstract observer (abstract class, easy to extend) stores the observer object in a container. This class provides some interfaces, such as adding observers, canceling observers, and notifying observers (notify )
  • Concrete observer (concrete class, inherits the abstract class of the observed) Stores the observer that needs to be notified. When the observer needs to update, call the notify method
  • Abstract observer (interface or abstract class) is concrete Observers provide an updated interface and update when notified by the observer
  • Concrete observer (concrete class, inherit or implement abstract observer) implements the interface of abstract observer and automatically updates

phpDemo

Abstract observer

<code><span><?php </span><span>abstract</span><span><span>class</span><span>EventGenerator</span>{</span><span>private</span><span>$observer_arr</span> = <span>array</span>();

    <span>/*
        添加观察者
     */</span><span>public</span><span><span>function</span><span>addObserver</span><span>( Observer <span>$observer</span>)</span>
    {</span><span>$this</span>->observer_arr[] = <span>$observer</span>;
    }

    <span>/*
        通知所有观察者
     */</span><span>public</span><span><span>function</span><span>notify</span><span>()</span>
    {</span><span>foreach</span> (<span>$this</span>->observer_arr <span>as</span><span>$observer</span>) 
        {
            <span>$observer</span>->update();
        }
    }

}
</span></code>

Concrete observer

<code><span><span>class</span><span>Event</span><span>extends</span><span>EventGenerator</span>{</span><span>public</span><span><span>function</span><span>trigger</span><span>()</span>
    {</span><span>echo</span><span>'event happen!<br>'</span>;
        <span>//当事件发生时,通知所有观察者</span><span>$this</span>->notify();
    }

}
</code>

Abstract observer

<code><span><?php </span><span><span>interface</span><span>Observer</span>{</span><span>//自动更新</span><span><span>function</span><span>update</span><span>()</span>;</span>
}

</span></code>

Concrete observer

<code><span><span>class</span><span>Observer1</span><span>implements</span><span>Observer</span>{</span><span>//实现update方法</span><span>public</span><span><span>function</span><span>update</span><span>()</span>
    {</span><span>echo</span><span>'observer1 update<br>'</span>;
    }
}

<span><span>class</span><span>Observer2</span><span>implements</span><span>Observer</span>{</span><span>//实现update方法</span><span>public</span><span><span>function</span><span>update</span><span>()</span>
    {</span><span>echo</span><span>'observer2 update<br>'</span>;
    }
}

</code>

Test code

<code><span>$obj</span> = <span>new</span> Event();
<span>//添加观察者</span><span>$obj</span>->addObserver(<span>new</span> Observer1());
<span>$obj</span>->addObserver(<span>new</span> Observer2());
<span>$obj</span>->trigger();
</code>

Pattern summary

  • Advantages: The observer pattern implements low coupling, non-intrusive notification and automatic updates Mechanism
  • Disadvantages: The dependency relationship is not completely eliminated, the abstract notifier still relies on the abstract observer
  • Trial scenarios: 1. When a change in an object requires changing other objects, and it does not know how many objects are waiting. When changing; 2. An abstract type has two aspects. When one aspect depends on the other aspect, the observer pattern can be used to encapsulate the two in independent objects so that they can be changed and reused independently.

The above introduces the observer pattern, one of the PHP design patterns, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
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
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version