when to use the observer pattern when developing websites?
i need some practical examples of cases when i could use the observer pattern when developing a website.. (using php)
I have one "when a user publishes an Article (subject), the class RSS and the class EMAIL (the observers) will modify the rss and send an email to the admin", but i'm not even sure if this is a good example..
where are you using the observer pattern?
BTW: this is not a homework, i was just lying here thinking about this pattern :)
EDITED I'm开发者_开发百科 more curious about the "WHEN to do it" and not the "HOW to do it"
I have a collection (array) of objects (cells) as the property of a "cellCollection" object. To reduce memory usage, each cell is actually held in serialized form in a cache (disk file, APC, memcache, whatever) while the "cellCollection" object holds its array of pointers to the cache location. I use the observer pattern so that the "cellCollection" object is notified whenever a "cell" object is modified, so that it can update the master copy of that "cell" object in cache and adjust its pointers as necessary.
You typically do not need the observer pattern in more or less state-free PHP.
However, consider the following. I skipped some code but you should be able 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);
}
}
}
I use it every time an 'action' happens. These things include the basic CRUD on every kind of entity (user, content, tags etc), but many other operations (user login, user logout, module load, module exit etc).
I also prefer using the Visitor
pattern after something gets loaded or before something gets saved (inserted or updated to the database) or before something (eg a form) gets rendered to alter the structure of the data.
Actions can happen multiple times in a page load.
精彩评论