Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Option Laravel Package

php-standard-library/option

Option type for PHP with Some/None to replace nullable values with explicit presence semantics. Helps avoid null checks, clarifies intent, and models optional data safely. Part of PHP Standard Library; see docs and contributing links.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/option
    

    Add to composer.json if using a monorepo or custom package:

    "require": {
        "php-standard-library/option": "^1.0"
    }
    
  2. First Use Case Replace a nullable return type with an explicit Option type:

    use PhpStandardLibrary\Option;
    
    function findUserById(int $id): Option {
        $user = User::query()->find($id);
        return Option::some($user) ?? Option::none();
    }
    
    // Usage
    $userOption = findUserById(1);
    if ($userOption->isSome()) {
        $user = $userOption->unwrap(); // User object
    } else {
        // Handle absence explicitly
    }
    
  3. Key Files

    • src/Option.php (Core class)
    • src/OptionTrait.php (For extending existing classes)

Implementation Patterns

Core Workflows

  1. Type Safety Use Option instead of ?Type for:

    function getConfigValue(string $key): Option {
        return config()->has($key) ? Option::some(config($key)) : Option::none();
    }
    
  2. Method Chaining Leverage map, filter, and flatMap for functional-style operations:

    $result = Option::some($user)
        ->map(fn($u) => $u->email)
        ->filter(fn($e) => str_contains($e, '@example.com'));
    
  3. Integration with Laravel

    • Service Providers: Return Option from boot methods:
      public function boot(): Option {
          return Option::some($this->app->make(SomeService::class));
      }
      
    • Eloquent: Replace first() with Option:
      $user = User::where('active', true)->firstOption();
      
  4. Custom Collections Extend Collection to add firstOption():

    use PhpStandardLibrary\Option;
    
    class OptionCollection extends Collection {
        public function firstOption(): Option {
            return $this->isEmpty() ? Option::none() : Option::some($this);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Null Confusion

    • Option::none() is not null. Avoid mixing:
      // ❌ Anti-pattern
      $option = Option::some(null); // Valid but misleading
      if ($option->unwrap() === null) { // Unreliable
      }
      
    • Fix: Use isNone() or unwrapOrDefault().
  2. Performance

    • Overusing Option in tight loops may add overhead. Benchmark critical paths.
  3. IDE Support

    • Some IDEs (e.g., PHPStorm) may not auto-detect Option types. Use PHPDoc:
      /** @return Option<User> */
      function findUser(): Option { ... }
      

Debugging

  • Inspecting Options
    $option->isSome(); // bool
    $option->isNone(); // bool
    $option->unwrapOr($default); // mixed
    
  • Common Errors
    • UnwrapError: Caught via try-catch:
      try {
          $value = $option->unwrap();
      } catch (UnwrapError $e) {
          // Handle absence
      }
      

Extension Points

  1. Custom Matching Extend Option for domain-specific logic:

    Option::match(
        $option,
        fn($value) => "Found: $value",
        fn() => "Not found"
    );
    
  2. Interop with Nullables Convert between Option and ?Type:

    $nullable = $option->toNullable(); // ?Type
    $option = Option::fromNullable($nullable); // Option<Type>
    
  3. Laravel-Specific

    • Request Handling:
      $value = Option::fromNullable(request()->input('optional_field'));
      
    • Validation:
      $option = Option::some($request->input('required_field'))
          ->filter(fn($v) => strlen($v) > 3);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation