欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-04-07 23:30:09
...
详解PHP装饰模式的示例代码
<?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);

以上就是详解PHP装饰模式的示例代码的详细内容,更多请关注其它相关文章!

相关标签: PHP,装饰模式