Download the PHP package ekiwok/option without Composer
On this page you can find all versions of the php package ekiwok/option. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download ekiwok/option
More information about ekiwok/option
Files in ekiwok/option
Package option
Short Description PHP Option implementations for all scalars. Possible to register custom Option.
License MIT
Informations about the package option
PHP Option
Option is a value that might or might not be present. In other words it's elegant alternative to throwing an exception or allowing method to return null. It allows for fluent chaining method calls.
Instead of either:
Just have:
Allow null approach:
Option approach:
In contrary to other libraries this one implements separate Option for each scalar type and allows registering custom Options for objects. It's the closest to Java templates we can get and enforces strict type checking.
So if you prefer strict type checking over having a few opcodes less, you can enforce:
Optional::Some
wraps each value to correct Option
Installation
With composer: composer require ekiwok/option
Interface
All scalar options enforce that methods get
, orElse
, orElseGet
, orElseThrow
returns the same scalar.
So it's not possible to orElse
float from OptionString:
The only exception is Optional
which does not enforce types.
Important thing to notice is that when you map Option which is None it will return Optional.
This is because there is no reasonable way to guess what should be the type of the value returned by a $supplier. In Some we are able to wrap accordingly to the type of the returned value.
On top of that you probably do not care about mapping when you're dealing with None because all further mappings will also return None.
But if you really want to ensure that, for example, orElseGet
$supplier returns value of correct type you might provide expected type as another map parameter:
Custom mappings
Simply register custom mappings:
Any
If you don't want to get specific type like, for example, OptionString you can wrap $value into Any
Autogenerating options
There is experimental bin/generator.php
for autogenerating custom Option classes.
It accepts full class name (including namespace) as first argument and optionally desired namespace as second argument (if not provided default namespace is class namespace prefixed with autoload).
So to generate OptionDateTime one could do:
vendor/ekiwok/opion/bin/generator.php \DateTime > ./autogenerated/OptionDateTime.php