开发者

Error handling in PHP

开发者 https://www.devze.com 2022-12-28 07:29 出处:网络
We\'re building a PHP app based on Good old codeigniter framework and have run into trouble with a massive chained action that consists of multiple mo开发者_开发问答del calls, that together is a part

We're building a PHP app based on Good old codeigniter framework and have run into trouble with a massive chained action that consists of multiple mo开发者_开发问答del calls, that together is a part of a big transaction to the database.

We want to be able to do a list of actions and get a status report of each one back from the function, whatever the outcome is.

Our first initial idea was to utilize the exceptions of PHP5, but since we want to also need status messages that doesn't break the execution of the script, this was our solution that we came up with.

It goes a little something like this:

$sku = $this->addSku( $name );

if ($sku === false) {
    $status[] = 'Something gone terrible wrong';
    $this->db->trans_rollback();
    return $status;
} 

$image= $this->addImage( $filename);

if ($image=== false) {
    $error[] = 'Image could not be uploaded, check filesize';
    $this->db->trans_rollback();
    return $status;
} 

Our controller looks like this:

$var = $this->products->addProductGroup($array);

if (is_array($var)) {

    foreach ($var as $error) {
        echo $error . '<br />';
    }

}

It appears to be a very fragile solution to do what we need, but it's neither scalable, neither effective when compared to pure PHP exceptions for instance.

Is this really the way that this kind of stuff generally is handled in MVC based apps?

Thanks!

UPDATE: Have done a fair share of googling and found this PHP Function: register_shutdown_function. Could it be what we are looking for? I have no Idea and can't get it working the way we want it to... Reference: http://php.net/manual/de/function.register-shutdown-function.php


You can set a custom exception handler in PHP - http://php.net/manual/en/function.set-exception-handler.php

This will allow the script to continue executing. YOu could create a function that logs the status into a database. Another function and/or class could fetch these to update the current status report. If you throw a custom exeption i.e..throw StatusException, your custom handler could pick up on the exception type and log it appropriately while doing default actions for other standard exceptions...

Alternatively from using the database you could use the exception handler to store the information into a session object etc to be referenced later on just for the current session.

If using an Exception handler is the right thing i'm still not sure as I'm still a bit vague on what you're trying to do but my method would allow code execution to continue while handling exceptions.

0

精彩评论

暂无评论...
验证码 换一张
取 消