开发者

when to use the observer pattern when developing websites?

开发者 https://www.devze.com 2023-01-14 08:11 出处:网络
i need some practical examples of cases when i could use the observer pattern when developing a website.. (using php)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号