A PHP implementation of the Optional pattern, inspired by Java's java.util.Optional
.
This library provides a container object which may or may not contain a non-null value, helping to avoid null pointer exceptions and improve code readability.
You can install this library using Composer. Run the following command in your project directory:
composer require jdecool/optional
If you're not using Composer, you can download the library files and include them manually in your project. Make sure to set up the appropriate autoloading for the JDecool\DataStructure
namespace.
Creates an Optional with a non-null value.
use JDecool\DataStructure\Optional;
$optional = Optional::of('Hello, World!');
Creates an Optional that may contain a null value.
$optional = Optional::ofNullable(null);
Creates an empty Optional.
$emptyOptional = Optional::empty();
Performs an action if the Optional contains a non-null value;
$optional->ifPresent(static fn ($value) => echo "Optional contains a value.");
Performs the given action with the value, otherwise performs the given empty-based action.
$optional->ifPresentOrElse(
static fn ($value) => echo "Optional contains a value.",
static fn () => echo "Optional doesn't contains a value.",
);
Checks if the Optional contains a non-null value.
if ($optional->isPresent()) {
echo "Value is present";
}
Checks if the Optional is empty (contains null).
if ($optional->isEmpty()) {
echo "Optional is empty";
}
Retrieves the value if present, throws a NoSuchElementException
if empty.
try {
$value = $optional->get();
} catch (NoSuchElementException $e) {
echo "No value present";
}
Filters the Optional based on a predicate.
$filtered = $optional->filter(fn($value) => strlen($value) > 5);
Transforms the Optional's value using a mapping function.
$mapped = $optional->map(fn($value) => strtoupper($value));
Returns the Optional if it has a value, otherwise returns the provided Optional.
$result = $optional->or(Optional::of('Default'));
Returns the Optional's value if present, otherwise returns the provided value.
$value = $optional->orElse('Default');
Returns the Optional's value if present, otherwise returns the result of the callable.
$value = $optional->orElseGet(fn() => 'Default');
Returns the Optional's value if present, otherwise throws the provided exception.
try {
$value = $optional->orElseThrow(new Exception('Value not present'));
} catch (Exception $e) {
echo $e->getMessage();
}
Compares this Optional to another object for equality.
$isEqual = $optional->equals(Optional::of('Hello, World!'));
This Optional library provides a robust way to handle potentially null values in your PHP code, reducing the risk of null pointer exceptions and improving overall code quality.