详解PHP装饰模式的示例代码

黄舟
发布: 2023-03-06 17:00:01
原创
1238 人浏览过

详解PHP装饰模式的示例代码

<?php  
// 装饰模式  
  
function echoLine($msg) {    
    echo $msg, &#39;<br/>&#39;;    
}  
  
class RequestHelper  
{  
    /** 
     * return class resource id 
     */  
    public function toString()  
    {  
        ob_start();  
        var_dump($this);  
        $str = ob_get_clean();  
        if (preg_match(&#39;/object\(&#39; . CLASS . &#39;\)\#\d+/&#39;, $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(&#39;Process http request[&#39; . $req . &#39;]&#39;);  
    }  
}  
  
/** 
 * 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(&#39;Add log function!&#39;);  
        $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(&#39;Add authenticate function!&#39;);  
        $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);
登录后复制

以上是详解PHP装饰模式的示例代码的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板