PHP exceptions in classes

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;
        }



    }
+5
4

A PHP void.

public function __construct()
{
    return FALSE;
}

.

public function __construct($camperId)
{
    if($camperId === 1) {
        throw new Exception('ID 1 is not in database');
    }
}

script, -

try { 
    $camper = new SummerCamper(1);
} catch(Exception $e) {
    $camper = FALSE;
}

SummerCamper , , new ( Java, )

class SummerCamper
{
    protected function __construct($camperId)
    {
        if($camperId === 1) {
            throw new Exception('ID 1 is not in database');
        }
    }
    public static function create($camperId)
    {
        $camper = FALSE;
        try {
            $camper = new self($camperId);
        } catch(Exception $e) {
            // uncomment if you want PHP to raise a Notice about it
            // trigger_error($e->getMessage(), E_USER_NOTICE);
        }
        return $camper;
    }
}

,

$camper = SummerCamper::create(1);

FALSE $camper, $camper_id . , , Factory.

- SummerCamper. , SummerCamper - , SummerCamper. , , ActiveRecord RowDataGateway. DataMapper:

class SummerCamperMapper
{
    public function findById($id)
    {
        $camper = FALSE;
        $data = $this->dbAdapter->query('SELECT id, name FROM campers where ?', $id);
        if($data) {
            $camper = new SummerCamper($data);
        }
        return $camper;
    }
}

class SummerCamper
{
    protected $id;
    public function __construct(array $data)
    {
        $this->id = data['id'];
        // other assignments
    }
}

DataMapper , , . , .

+11

, , -:

try {
    $camper = new SummerCamper($camper_id);
} catch (NoRecordsException $e) {
    // handle no records
} catch (InvalidDataException $e) {
    // handle invalid data
}
+4

Throwing an exception from the constructor is probably the right approach. You can catch it in the appropriate place and take the necessary actions (for example, display a page with an error). Since you did not show any code, it is not clear where you caught your exception or why this does not work.

+1
source
try {
    $camper = new SummerCamper($id);
    $camper->display();
} catch (NonexistentCamper $ex) {
    handleFailure($ex);
}
+1
source

All Articles