在開發應用程式時,您經常需要應用程式能夠靈活地對事件做出反應。例如,假設您希望在發生某些操作(例如使用者註冊)時通知多個系統。這就是模式觀察者的用武之地。此模式可讓您在物件之間建立一種關係,以便當一個物件的狀態發生變化時,所有其他物件都會自動通知並更新。
借助事件調度程序,Symfony 已經有效地實現了此模式,這使得它在您的專案中使用起來非常實用且強大。
模式觀察者可讓您定義被觀察主體與一個或多個觀察者之間的關係。當被觀察對象發生狀態變化時,所有觀察者都會收到通知,以便他們做出相應的反應。
工作原理如下:
假設您有一個使用者可以註冊的網站。每次註冊時,您都需要發送一封歡迎電子郵件,將使用者新增至電子報清單並通知分析系統。
您可以將這些任務委託給不同的觀察者,而不是在一個地方嚴格編碼所有內容,一旦觸發「註冊用戶」事件,他們就會收到通知。
在 Symfony 中,您將使用事件調度程式來設定模式觀察器。這將使您能夠整齊地組織程式碼並使其可擴展,而無需修改基本邏輯。
我們將首先建立一個事件,該事件將在使用者註冊時調度。後者將包含用戶的信息。
現在,在您的控制器或服務中,您將在使用者註冊時調度此事件。
接下來,您必須建立觀察者,每次調度註冊事件時都會呼叫觀察者。在這裡,您有一個範例,我們發送電子郵件並將用戶新增到新聞通訊清單中。
您現在必須在設定中註冊偵聽器,以便它們偵聽 user.registered 事件。
在 config/services.yaml 中,將觀察者加入為服務:
ℹ️ 從 Symfony 5.3 版本開始,您可以使用 PHP 屬性來設定服務和事件偵聽器。這是一種更現代的方法,可讓您直接在類別中聲明事件,而不是使用 services.yaml 檔案。
因此,您可以直接在偵聽器方法上使用 #[AsEventListener] 屬性。
我將向您展示如何使用屬性調整兩個觀察者(因此不需要在 config/services.yaml 中進行特殊配置?:
When you register a user with the RegistrationController, the event is dispatched and Symfony automatically calls the corresponding observers. The email is sent, and the user is added to the newsletter list without these actions/logic being mixed with your business code.
Because it's an essential! It will allow your application to be:
The Pattern Observer often finds its place in architectures based on DDD (Domain-Driven Design), where events are key elements (Domain Events). These events allow different parts of the system to react, often outside the main domain. But that’s a discussion for a future full article on DDD!
以上是設計模式觀察者:強大的通知系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!