php-設計模式之觀察者模式

使用觀察者模式實現用戶註冊。註冊成功後臺處理髮郵件,處理詳情等業務。

 

觀察者模式的原理這裏就不寫了。php要實現觀察者模式,需要實現兩個接口。具體代碼如下:

 

  //用戶類

class User implements SplSubject
{

    //觀察者模式 通知狀態
    public $status = null;  // 1 註冊成功 2 登錄成功
    public $observers = null;
    public $attr = null;   //用戶屬性

    function __construct()
    {
 
        $this->observers = new \SplObjectStorage();
    }

    
    function register(string $account, string $pwd, array $info = [])
    {
        //檢查用戶名是否重複
        if(!$this->user->checkAccount($account)){   //業務代碼
            return [[],U_ERROR_ACCOUNT_REPEAT_FAIL];
        }
        
        $item['id_example'] = $exampleId;
        $item['account'] = $account;
        $item['openid']  = $account;
        $item['type']  =  $type;
        $userObj = $this->user->addItem($item,1);   //業務代碼


        $this->status = 1;
        $this->attr = $info;
        $this->attr['id_user']= $userObj->id;
        $login_key = $this->loginSuccess();

        return [$user,$login_key];
    }



    function login(string $account, string $pwd ,int $type = 3)
    {
        $userObj = $this->user->getItemByAccount($account);

        //賬戶密碼登錄 驗證密碼
        if($type == 3){
            $pwdr =  Pwd::getPass($pwd,$userObj->acode);
            if(!$pwdr == $userObj->password){
                return [[],U_ERROR_ACCOUNT_PWD_ERROR];
            }
        }

        $this->status = 2;
        $this->attr['id_user']= $userObj->id;
        $login_key = $this->loginSuccess();
        return [$userObj,$login_key];

    }





    function loginSuccess(){
        //觀察者模式  註冊成功 之後 相關操作

        //註冊詳情
        $this->attach(new UserInfo());
        //發送郵件
        $this->attach(new Email());

        $this->notify(); 
    }

    public function attach(SplObserver $observer)
    {
        $this->observers->attach($observer);
    }

    public function detach(SplObserver $observer)
    {
        $this->detach($observer);
    }

    public function notify()
    {
       $this->observers->rewind();
       foreach($this->observers as $observer){
           //用戶相關操作
           $observer->update($this);
       }
    }

//用戶詳情類

class UserInfo implements \SplObserver
{
  
   


    //處理用戶註冊、登錄後的操作
    public function update(SplSubject $subject)
    {

        //註冊
        if($subject->status == 1){
            //註冊用戶相關信息
           
        //登錄
        }else{
            //更新最後登錄時間
           
        }
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章