This is a PHP interpretation of the Option type with monadic structure. We beleive that the tests document the behavior and even though the implementation is similar to php-option there are some important differences we need to highlight.
We found it useful, that the monadic computation may decide to return with an arbitrary type, that will be converted to an Option if necessary.
The rules for Some::apply
is as follows:
- If the return type is not an Option it will be wrapped in Some
- If there is no return value (actually the return value is null) it will be translated to None
- If the return type is an Option it will be passed through (the same as for flatMap)
Wrapping a non Option type:
$result = someMethodReturningAnOptionalString($params)
->apply(
function ($result) {
return $result . ' is a string!';
})
->getOrElse('default');
No need to explicitly return with None:
$module = $dataMaybe
->apply(
function ($data) {
if (isset($data['moduleConfig'])) {
if (count($data['moduleConfig']) == 1) {
return key($data['moduleConfig']);
} elseif (count($data['moduleConfig']) > 1) {
return 'full';
}
}
}
)
->getOrElse('unknown');
We use None::otherwise
as the mirror of Some::apply
.
Combining apply and otherwise:
header(
locate($_SERVER["DOCUMENT_URI"])
->apply(
function ($location) {
statsdIncrement('302');
return 'Location: ' . $location;
}
)
->otherwise(
function () {
statsdIncrement('404');
}
)
->getOrElse("HTTP/1.0 404 Not Found")
);
Creating a chain of fallback functions:
return Ustream\Option\None::create()
->otherwise($this->ustreamPicture($userId, $size))
->otherwise($this->facebookPictureFromSession($facebookNetwork, $isSecureAccess))
->getOrElse($this->naPicture($size));