Hi, I have just started OOP style programming and have made my first class. Could you be kind enough to have a look and see if I am using the right 'philosophy'? I have been doing procedural style for ages and it is difficult thinking in a different way.
the code works perfectly well but it is the 'philosophy' behind it that I am unsure about. Have I gone about it the right way? Is my approach completely off the wall?
The class it self explanatory and simply takes an uploaded file and a name. As it goes through the verifyImage function, it will exit if there is an error. If no error then it carries on.
I have called it this way in my main page:
require_once('newImage.php');
$image = new newImage($_FILES['image']['size'], $_FILES['image']['type'], $_FILES['image']['tmp_name'], $_POST['name']);
if ($image->verifyImage()) {
$image->moveImage();
}
The class is as follows:
class NewImage {
private $size;
private $type;
private $oldName;
private $newName;
function __construct($size, $type, $oldName, $newName) {
$this->size = $size / 1000;
$this->type = $type;
$this->oldName = $oldName;
$this->newName = trim(stripslashes(strip_tags($newName)));
} // end function __construct
function verifyImage() {
// Check for blank upload.
try {
if ($this->size == 0){
throw new exception ("<p>You forgot to upload an image.</p>");
}
} catch (exception $error) {
echo $error->getmessage();
return;
}
// Ensure upload is a valid mime type.
$mimeTypes = array ("image/jpeg","image/pjpeg");
try {
if (!in_array ($this->type,$mimeTypes)){
throw new exception ("<p>The image must be a jpg. Yours is an: " . $this->type . "</p>");
}
} catch (exception $error) {
echo $error->getmessage ();
return;
}
// Check for the file size.
try {
if ($this->size > 90) {
//Echo an error message.
throw new exception ("The file is too big at " . $this->size . "KB");
}
} catch (exception $error) {
echo $error->getmessage();
return;
}
// Check for a blank newName.
try {
if ($this->newName == '') {
throw new exception ("<p>You forgot to enter a name for the image.</p>");
}
} catch (exception $error) {
echo $error->getmessage();
return;
}
// Convert spaces to underscores in the image newName
try {
if (!$this->newName = preg_replace('/ /', '_', $this->newName)) {
throw new exception ("<p>There was an error converting the image name</p>");
}
} catch (exception $error) {
echo $error->getmessage();
return;
}
return true;
} // end function verifyImage()
function moveImage() {
//move image with the newName.
try {
if (!move_uploaded_file ($this->oldName,"uploads/". $this->newName.".jpg")) {
throw new exception ("There was an error moving the file.");
}
} catch (exception $error) {
echo $error->getmessage ();
return;
}
return true;
} // end function moveImage
} // end class NewImage
Just because it works does not mean it is the best way to go about it so any thoughts gratefully appreciated!