Is there a better way to write this code.
Suppose I have 10 files to delete and I have to repeat code (public function destroy()
) 10 times.
- First remove the database entry.
- List item, then remove the file.
OOP - "don't repeat yourself", it works but I repeat the code.
public function image_path() {
return $this->upload_dir .DS. $this->filename;
}
public function image_path2() {
return $this->upload_dir .DS. $this->filename2;
}
public function destroy() {
if($this->delete()) {
$target_path = PUBLIC_PATH.DS.'public'.DS.$this->image_path();
return unlink($target_path) ? true : false;
} else {
return false;
}
}
public function destroy2() {
if($this->delete()) {
$target_path2 = PUBLIC_PATH.DS.'public'.DS.$this->image_path2();
return unlink($target_path2) ? true : false;
} else {
return false;
}
}
delete_photo.php
// Delete photo
$result = $photo->destroy();
$result = $photo->destroy2();
photo class
public function delete() {
global $database;
$sql = "DELETE FROM " . self::$table_name . " ";
$sql .= "WHERE id='" . $database->escape_value($this->id) . "' ";
$sql .= "LIMIT 1";
$result = $database->query($sql);
return $result;
}
protected static $db_fields=array('id', 'filename', 'filename2', 'type', 'type2','size', 'size2', 'caption');
public $id;
public $filename;
public $filename2;
public $type;
public $type2;
public $size;
public $size2;
public $caption;
$filename1
and$filename2
\$\endgroup\$$filename1
and$filename2
to upload 2 or more files. \$\endgroup\$