I am writing a web application (PHP) for my friend and decided to use my limited OOP training with Java.
My question is the best way to point out in my class / application that certain critical things failed without breaking my page.
My problem is that I have a SummerCamper object that takes camper_id as an argument to load all the necessary data into the object from the database. Say someone points to camper_id in the query string that does not exist, I pass it to the constructor of the objects and the download fails. Currently, I see no way to return false from the constructor.
I read that I could do this with Exceptions, throwing an exception if there are no records in the database, or if some kind of check fails when entering camper_id from the application, etc.
However, I really did not find a great way to warn my program that the loading of the object failed. I tried to return false from CATCH, but Object is still stored in my php page. I understand that I can put the variable $ is_valid = false if the download failed, and then check the object using the get method, but I think there may be better ways.
What is the best way to achieve substantial completion of an object if the load fails? Should I load data into an object from outside the constructor? Is there any design I need to learn?
Any help would be appreciated.
function __construct($camper_id){
try{
$query = "SELECT * FROM campers WHERE camper_id = $camper_id";
$getResults = mysql_query($query);
$records = mysql_num_rows($getResults);
if ($records != 1) {
throw new Exception('Camper ID not Found.');
}
while($row = mysql_fetch_array($getResults))
{
$this->camper_id = $row['camper_id'];
$this->first_name = $row['first_name'];
$this->last_name = $row['last_name'];
$this->grade = $row['grade'];
$this->camper_age = $row['camper_age'];
$this->camper_gender = $row['gender'];
$this->return_camper = $row['return_camper'];
}
}
catch(Exception $e){
return false;
}
}