When to use the observer pattern when designing websites?

I need some practical examples of cases where I could use the observer pattern when designing a website .. (using php)

I have one , when a user publishes an article (topic), the RSS class and the EMAIL class (observers) will change the rss and send an email to the administrator, " but I'm" Not even sure if this is a good example. "

where do you use the observer pattern?

By the way: this is not homework, I just lay here thinking about this template :)

EDITED I'm more curious, "WHEN I need it," rather than HOW to do it

+4
source share
3 answers

I have a collection (array) of objects (cells) as a property of a cellCollection object. To reduce memory usage, each cell is actually stored in serialized form in the cache (disk file, APC, memcache, independently), while the cellCollection object contains its own array of pointers in the cache location. I use an observer pattern so that the cellCollection object is notified whenever the cell object is modified, so that it can update the main copy of this mesh object in the cache and adjust its pointers if necessary.

+2
source

Usually you do not need an observer pattern in more or less free of PHP language.

However, consider the following. I skipped the code, but you have to fill in the blanks.

class Stats extends Observer implements SplObserver { private function updateStats($action) { } public function update(SplSubject $subject) { if ($subject instanceOf Article) { if ($subject->notice == Article::NOTICE_POSTED_ARTICLE) { $this->updateStats($subject->notice); } } } } class Article extends Subject implements SplSubject { const NOTICE_POSTED_ARTICLE = "Article Posted"; private $observers; public $notice; public function postArticle($text) { $this->notice = self::NOTICE_POSTED_ARTICLE; $this->notify(); } public function notify() { foreach ($this->observers as $observer) { $observer->update($this); } } } 
+1
source

I use it every time an action occurs. These things include a basic CRUD for each type of entity (user, content, tags, etc.), but many other operations (user login, user logout, module loading, module exit, etc.).

I also prefer to use the Visitor template after something is loaded or before something is saved (inserted or updated in the database) or before something (for example, a form) is rendered to change data structure.

Actions can be performed several times when the page loads.

0
source

All Articles