设计模式之适配器

class LogException extends Exception
{

}

interface Log
{
    public function write($msg);
    public function read();
}

class Logger // 日志内容对象
{
    public function setType($type)
    {
        $this->type = $type;
    }

    public function getType()
    {
        return $this->type;
    }

    public function queue($msg)
    {
        $this->queue[] = $msg;
    }
}

class FileLog implements Log
{
    public function __construct($file)
    {
        $this->file = $file;
    }

    public function read()
    {
        return 'read form ' . $this->file; 
    }

    public function write($msg)
    {
        if (is_string($msg)) {
            echo $msg . ' is written to file ' . $this->file;            
        } else {
            var_dump($msg);
        }
    }
}

class DbLog
{
    public function loadAdapter(Log $fileLog)
    {
        $this->fileLog = $fileLog;
    }

    public function writeToDb(Logger $logger)
    {

        $content = $this->fileLog->read();

        $lines = json_encode($logger->queue) . ' ' . $logger->getType();
        $this->fileLog->write($lines);

        echo ' write "' . $content . '" to db...' . PHP_EOL;
    }
}

$logger = new Logger();
$logger->setType('api test');
$logger->queue('haha');

$dblog = new DbLog();
$dblog->loadAdapter(new FileLog('test')); // FileLog作为适配器,DbLog从FileLog取出数据写入数据库

$dblog->writeToDb($logger);

标签: none