Home  >  Article  >  Backend Development  >  Detailed explanation of PHP decoration mode sample code

Detailed explanation of PHP decoration mode sample code

黄舟
黄舟Original
2017-03-16 09:24:061215browse

Detailed explanation of the sample code of PHP decoration mode

<?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);

The above is the detailed content of Detailed explanation of PHP decoration mode sample code. 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