Download the PHP package skd/result without Composer
On this page you can find all versions of the php package skd/result. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Package result
Short Description Implementing the Result Object pattern in PHP
License MIT
Informations about the package result
The Result object
This package allows you to work with the results of operations, including errors, in an object-oriented style, without using exceptions. For example, when using the 'Always valid domain model' approach. Result object allows you to accumulate errors and return them all at once (Notification pattern is inside). At the same time, the code becomes more understandable and logical.
Installation
Result
The Result class is an immutable generic class (using @template
annotation) with 2 states: Ok
and Error
.
The OK
state means that there are no errors inside and there is some value (success operation result).
The Error
state means that an error or several errors were received during the operation.
Use @return Result<type_or_class>
annotation to tell the IDE and static analysis tool what type value is inside;
Ok state
Use static method Result::ok
to return success operation result with some value inside
Use method Result::getValue(): T
to get the value. Note that calling this method on Error state
will throw an exception. To prevent that you have to check the result state by calling one of methods
Result::isOk(): bool
or Result::isError(): bool
before.
Error state
Use static method Result:error(Notification $errors)
to return result with an error (errors). The non-empty Notification
object must be passed as an argument. Passing an empty Notification object (no errors inside) will throw an exception.
Use method Result::getErrors(): Notification
to get an error (errors). Note that calling that method on
Ok
state will throw an exception. You can't change Notification object after Result object is initialized
Notification
Notification class is a Notification pattern realisation. It can be initialized in two ways: as an empty list or a list with one error inside
Use method Notification::hasErrors(): bool
to check if there are error/errors inside the notification object
Use method Notification::hasError(Error $error): bool
to check if the specific error is inside the notification object.
It can be useful in Unit tests.
Errors Accumulating
Errors can be accumulated in a Notification object.
Use Notification::addError(Error $error): void
to add some error in the list
Notification objects can be merged as well. It can be useful when you have to accumulate two or more results with errors. Note that only left object will be changed.
Example:
Some Value Object class
You can replace with static factory:
Unit tests