php-option Documentation

repository·master·Indexed 25 days ago

https://github.com/schmittjoh/php-option

A 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.

Tokens
829
Snippets
3
Records
4
Agent score
33%

What's inside php-option

  1. Try multiple alternative options with orElse()

    master

    You 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')));
  2. Retrieve values from an Option

    master

    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.
  3. Use the Option type in your API

    master

    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:

    1. Manual instantiation: Use new \PhpOption\Some($value) for present values and \PhpOption\None::create() for absent values.
    2. Using 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);
    }