According to you, what is the best solution in PHP to ensure the course of several php functions ? For example function A must return True to initiate the B function, and the B function must return True to initiate another function...

Is there a system like Rollback / Commit in SQL to ensure that in PHP please ?

Thank you.

Comments

some example code would be helpful ...

Written by DhruvPathak

You have to expand your question more and prove code....

Written by Awais Qarni

Is it important that you roll back any changes made by these functions? And what do these functions do, the answer to your problem might even be to not use functions...

Written by klennepette

I think you are mixing two topics here: a chain of actions and a commit/rollback database schema. Answers below can cope with a chain of actions, but I have only seen commit/rollback operations within frameworks (e.g. CakePHP). Give us more information ;)

Written by elitalon

Accepted Answer

Doing a chain of functions would look something like this:

try {
    if(!functionA()) {
        throw new Exception("Error message here", 100); // 100 can be any code, as long as it's unique to the other throw exception codes
    }

    if(!functionB()) {
        throw new Exception("Error message here", 101);
    }

    if(!functionC()) {
        throw new Exception("Error message here", 102);
    }
} catch(Exception $e) { 
    /**
     * Do some actions depending on the error code of the exception (100, 101, 102)
     */
}

But if I understand correctly you want to perform a serie of operations and only if they are all successful you want them to be final, otherwise you want to undo all the operations?

In this case it is hard to tell how you should implement this, cause you don't tell what you want to achieve.

But I can give you some advise. Most operations that are not reversable do have many possible checks. For example, if you want to be sure a file will be deleted from the filesystem you can first check if the file is writable (is_writable) and even exists (file_exists). If you first do all the checks of all operations and afterwards execute the operations, you can be pretty sure they will be executed successfully. Ofcourse it's possible you forget checks, or some things can't be checked, but I don't see an other option to fix this.

Written by Rene Terstegen
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki