Install phpoption via Composer
masterYou can install the phpoption/phpoption package using Composer by running the following command in your terminal.
$ composer require phpoption/phpoptionrepository·master·Indexed 25 days ago
https://github.com/schmittjoh/php-optionA PHP implementation of the Option type for handling optional values safely using Some and None, providing methods like getOrElse(), getOrCall(), and orElse() to avoid null checks and control flow exceptions.
You can install the phpoption/phpoption package using Composer by running the following command in your terminal.
$ composer require phpoption/phpoptionYou can chain multiple options using the orElse() method. The first non-empty option in the chain will be returned.
To avoid the overhead of evaluating all alternatives immediately, use the LazyOption class. This ensures that subsequent options are only evaluated if the preceding ones are None.
// Standard chaining (evaluates all alternatives immediately)
return $this->findSomeEntity()
->orElse($this->findSomeOtherEntity())
->orElse($this->createEntity());
// Lazy chaining (only evaluates necessary alternatives)
return $this->findSomeEntity()
->orElse(new LazyOption(array($this, 'findSomeOtherEntity')))
->orElse(new LazyOption(array($this, 'createEntity')));Once you have an Option instance, you can retrieve the contained value using several methods depending on your requirements:
get(): Returns the value if present. Throws an exception if the option is None.getOrElse($default): Returns the value if present, otherwise returns the provided $default value.getOrCall(callable $callback): Returns the value if present, otherwise executes the provided callback and returns its result. This is useful for lazy evaluation of default values.When designing an API, you can return an Option to represent a value that might be present (Some) or absent (None).
There are two primary ways to implement this:
new \PhpOption\Some($value) for present values and \PhpOption\None::create() for absent values.Option::fromValue(): A shorthand method that treats null as None and everything else as Some. You can optionally specify a custom 'none' value (e.g., false).// Manual approach
public function findSomeEntity($criteria): \PhpOption\Option
{
if (null !== $entity = $this->em->find(...)) {
return new \PhpOption\Some($entity);
}
return \PhpOption\None::create();
}
// Shorthand approach
public function findSomeEntity($criteria): \PhpOption\Option
{
return \PhpOption\Option::fromValue($this->em->find(...));
// Or with a custom none value:
// return \PhpOption\Option::fromValue($this->em->find(...), false);
}