Detailed explanation of PHP decoration mode sample code

黄舟
Release: 2023-03-06 17:00:01
Original
1251 people have browsed it

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template