我试图检查ftp服务器上是否已经存在目录,如果它存在,那么它应该只创建并保存一个json文件到这个目录和return true
,如果它不存在,然后它应该首先创建目录并将json文件保存到目录,并return true
,否则它应该return false
。
我的代码目前如下所示:
<?php
// Function to create the outfit xml file
function create_outfit_json(){
if (!file_exists('../user/' . $this->Username)) {
mkdir('../user/' . $this->username, 0777, true);
$json['outfits'] = [];
$json['outfits']['0'] = [
'outfit' => [
'url' => 'placeholder',
'default' => 1,
'name' => 'New outfit',
'c' => '#bb9977',
'mood' => 3,
'species' => 'male'
]
];
$fp = fopen('../user/' . $this->Username . '/outfits.json', 'w');
fwrite($fp, json_encode($json));
fclose($fp);
return true;
}else if(file_exists('../user/' . $this->Username)){
$json['outfits'] = [];
$json['outfits']['0'] = [
'outfit' => [
'url' => 'placeholder',
'default' => 1,
'name' => 'New outfit',
'c' => '#bb9977',
'mood' => 3,
'species' => 'male'
]
];
$fp = fopen('../user/' . $this->Username . '/outfits.json', 'w');
fwrite($fp, json_encode($json));
fclose($fp);
return true;
}else{
return false;
}
}
?>
有没有办法让这段代码看起来更干净简洁?
答案 0 :(得分:0)
<?php
// Function to create the outfit xml file
function create_outfit_json(){
if (!file_exists('../user/' . $this->Username)) {
mkdir('../user/' . $this->Username, 0777, true);
}
$json['outfits']['0'] = [
'outfit' => [
'url' => 'placeholder',
'default' => 1,
'name' => 'New outfit',
'c' => '#bb9977',
'mood' => 3,
'species' => 'male'
]
];
$fp = fopen('../user/' . $this->Username . '/outfits.json', 'w');
fwrite($fp, json_encode($json));
fclose($fp);
}
}
?>
您不需要冗余代码 - 只需将mkdir
包装在一个if。
答案 1 :(得分:0)
阅读评论,总是用重用能力编写代码,
// Seperate all data and saving
function create_outfit_json(){
$json['outfits'] = [];
$json['outfits']['0'] = [
'outfit' => [
'url' => 'placeholder',
'default' => 1,
'name' => 'New outfit',
'c' => '#bb9977',
'mood' => 3,
'species' => 'male'
]
];
return $this->saveToDirectory(json_encode($json), 'outfits.json');
}
// passing data and filename will give you flexibility
function saveToDirectory($data, $filename){
if (!file_exists('../user/' . $this->Username)) {
mkdir('../user/' . $this->username, 0777, true);
}
// rather than opening connection let php do it for you
return file_put_contents('../user/'.$this->Username.'/'.$filename, $data);
}