本文主要是介绍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{//更新最后登录时间}} }
这篇关于php-设计模式之观察者模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!