Weave 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

Optional Laravel Package

petrknap/optional

Optional brings Java 8-style Optional to PHP, making null handling explicit and safe with isPresent(), get(), orElse(), and ifPresent(). Create strictly typed optionals for bools, strings, arrays, objects, and custom types using built-in traits with full static analysis support.

View on GitHub
Deep Wiki
Context7

Optional (like in Java Platform SE 8 but in PHP)

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.

-- Optional (Java Platform SE 8)

It is an easy way to make sure that everyone has to check if they have (not) received a null.

Basic usage

use PetrKnap\Optional\Optional;

/** @var Optional<string> $stringOption */
$stringOption = Optional::of('data');
if ($stringOption->isPresent()) {
    echo $stringOption->get();
}

Optional::ofFalsable(tmpfile())->ifPresent(function ($tmpFile): void {
    fwrite($tmpFile, 'data');
    fclose($tmpFile);
}, else: fn () => print('tmpfile() failed'));

Creating your own typed optional

The library provides specialized traits to help you implement strictly typed wrappers with full static analysis support.

Quick Overview

  1. NonGenericOptional trait for fixed specific types like bool or string (see OptionalString class)
    use PetrKnap\Optional\Optional;
    use PetrKnap\Optional\NonGenericOptional;
    
    /** @extends Optional<bool> */
    final class OptionalBool extends Optional
    {
        use NonGenericOptional;
    
        protected static function isSupported(mixed $value): bool
        {
            return is_bool($value);
        }
    }
    
  2. GenericOptional trait for generic structures like array (see OptionalArray class)
  3. AbstractOptional trait for extendable factory optionals (use this when you need a base class for other typed optionals, see OptionalObject class)

Type registration

You can register your custom typed optionals into TypedOptional helper. Once registered, calling the base Optional class will automatically look up and return the correct specific subclass if the value matches its criteria.

use PetrKnap\Optional\TypedOptional;
use PetrKnap\Optional\Optional;

TypedOptional::register(OptionalBool::class);

printf(
    "Class name of optional which holds `true` is `%s`.\n",
    get_class(Optional::of(true)),
);
Class name of optional which holds `true` is `OptionalBool`.

Run composer require petrknap/optional to install it. You can support this project via donation. The project is licensed under the terms of the LGPL-3.0-or-later.

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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style