Home  >  Article  >  Backend Development  >  Detailed code explanation of PHP's native support for the observer pattern

Detailed code explanation of PHP's native support for the observer pattern

黄舟
黄舟Original
2017-03-15 09:56:471095browse

Detailed code explanation of PHP’s native support for Observer pattern

<?php
// 观察者模式
// PHP(SPL)原生支持
/*
类摘要
SplSubject {
	abstract public void attach ( SplObserver $observer );
	abstract public void detach ( SplObserver $observer );
	abstract public void notify ( void );
}

SplObserver {
	abstract public void update ( SplSubject $subject );
}

SplObjectStorage implements Countable, Iterator, Serializable, ArrayAccess {
}
 */

class ConcreteSubject implements SplSubject
{
	private $storage;
	
	public function construct() {
		$this->storage = new SplObjectStorage();
	}
	
	public function attach(SplObserver $obs) {
		$this->storage->attach($obs);
	}
	
	public function detach(SplObserver $obs) {
		$this->storage->detach($obs);
	}
	
	public function notify() {
		foreach($this->storage as $ol) {
			$ol->update($this);
		}
	}
	
	public function doAct() {
		echo &#39;DoAct ... <br/>&#39;;
		$this->notify();
	}
}

/**
 * concrete observer 1
 */
class Observer1 implements SplObserver
{
	public function update(SplSubject $sub) {
		echo &#39;Observer one updated! <br/>&#39;;
	}
}

/**
 * concrete observer 2
 */
class Observer2 implements SplObserver
{
	public function update(SplSubject $sub) {
		echo &#39;Observer two updated! <br/>&#39;;
	}
}

// test code
$sub = new ConcreteSubject();

$sub->attach(new Observer1()); //add observer
$sub->attach(new Observer1());
$sub->attach(new Observer2());

$sub->doAct();

The above is the detailed content of Detailed code explanation of PHP's native support for the observer pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn