首頁  >  文章  >  後端開發  >  詳解PHP裝飾模式的範例程式碼

詳解PHP裝飾模式的範例程式碼

黄舟
黄舟原創
2017-03-16 09:24:061217瀏覽

詳解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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn