-
Notifications
You must be signed in to change notification settings - Fork 1
OperationResult
Simple class used to store the status message of any operation. It is meant to be used as return value of a method, to make it easy to check if the operation succeeded, and if not, access an error message.
One typical use case is a validation process, to store the validation message(s).
It comes in two variants:
-
OperationResult
to store a single status message. -
OperationResult_Collection
to store any amount of status messages.
The following class illustrates how OperationResult
can be used to store the result of an operation.
use AppUtils\OperationResult;
class OperationRunner
{
const ERROR_OP_FAILED = 10001;
function runOperation() : OperationResult
{
$result = new OperationResult($this);
// Do something which can fail gracefully, without having to
// throw an exception.
$success = false;
if($success) {
$result->makeSuccess('The operation was completed successfully.');
} else {
$result->makeError('The operation failed to run because of reasons.', self::ERROR_OP_FAILED);
}
return $result;
}
}
$runner = new OperationRunner();
$result = $runner->runOperation();
if($result->isError()) {
die('Operation runner failed: '.$result->getErrorMessage());
}
The result class is not meant as a replacement for exceptions. It is to be used in situations where a failed operation does not need the application to be halted. It stores information on the error (or even success of the operation), and allows this information to be used later.
A typical use case is a validation process: errors, warnings and notices can easily be stored (most likely directly as localized messages), and displayed in the UI later.
The OperationResult_Collection
class can be used as direct replacement of the
OperationResult
class. Every call to any of the makeXXX()
methods then adds a new
result to the collection. All methods like isError()
then take into account all
results that were added.
The addResult()
method can also be used to add an existing OperationResult
instance
to the collection, or even another collection (in which case its results are merged into
the collection).
Utility methods make it easy to work with all the stored results:
-
containsCode()
Is there a result with the specified code? -
countErrors()
Count the amount of errors. -
countWarnings()
Count the amount of warnings. -
countNotices()
Count the amount of notices. -
countSuccesses()
Count the amount of successful operations. -
getErrors()
Get all error results. -
getWarnings()
Get all warning results. -
getNotices()
Get all notices. -
getSuccesses()
Get all successful results.
New here?
Have a look at the overview for a list of all helper classes available in the package.
Table of contents
Find the current page in the collapsible "Pages" list above, and expand the page, to view a table of contents.