装饰模式

<?php
// 装饰模式

function echoLine($msg) {  
    echo $msg, '<br/>';  
}

class RequestHelper
{
	/**
	 * return class resource id
	 */
	public function __toString()
	{
		ob_start();
		var_dump($this);
		$str = ob_get_clean();
		if (preg_match('/object\(' . __CLASS__ . '\)\#\d+/', $str, $matches)) {
			return $matches[0];
		}
		return __CLASS__;
	}
}

// ---------------------------------------------------------

interface ProcessRequest
{
	public function process(RequestHelper $req);
}

/**
 * http request
 */
class HttpRequest implements ProcessRequest
{
	public function process(RequestHelper $req)
	{
		echoLine('Process http request[' . $req . ']');
	}
}

/**
 * Log Decorator
 * add log function
 */
class LogRequest implements ProcessRequest
{
	protected $pr;

	public function __construct(ProcessRequest $pr)
	{
		$this->pr = $pr;
	}
	
	public function process(RequestHelper $req)
	{
		echoLine('Add log function!');
		$this->pr->process($req);
	}
}

/**
 * Authenticate Decorator
 * add authenticate function
 */
class AuthenticateRquest implements ProcessRequest
{
	protected $pr;

	public function __construct(ProcessRequest $pr)
	{
		$this->pr = $pr;
	}
	
	public function process(RequestHelper $req)
	{
		echoLine('Add authenticate function!');
		$this->pr->process($req);
	}
}

// test code
$req = new RequestHelper();
$process = new HttpRequest();

// add log
$process = new LogRequest($process);
// add auth
$process = new AuthenticateRquest($process);

// process request
$process->process($req);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值