class JsonContentHandler extends ContentHandler
{
public function write(): bool
{
$json = json_encode($this->contents, JSON_UNESCAPED_UNICODE);
if (file_put_contents($this->source, $json) !== false) {
return true;
} else {
return false;
}
}
public function read(): bool
{
$json = file_get_contents($this->source);
if (!$json) {
return false;
}
$this->contents = json_decode($json, true);
return true;
}
}
2、XmlContentHandler
class XmlContentHandler extends ContentHandler
{
public function write(): bool
{
// TODO: 实现写入xml函数.
}
public function read(): bool
{
// TODO: 实现读取xml函数
}
}
3、ContentHandler
abstract class ContentHandler
{
protected $source;
protected $contents = [];
public function __construct($source)
{
$this->source = $source;
}
public function addContent(string $key, string $val)
{
$this->contents[$key] = $val;
}
public function getAllContents(): array
{
return $this->contents;
}
public static function getInstance(string $filename): ContentHandler
{
if (preg_match("/\.xml$/i", $filename)) {
return new XmlContentHandler($filename);
} elseif (preg_match("/\.json$/i", $filename)) {
return new JsonContentHandler($filename);
} else {
throw new Exception("暂不支持该文件类型");
}
}
abstract public function write(): bool;
abstract public function read(): bool;
}