PHP code example of wiz-develop / php-monad
1. Go to this page and download the library: Download wiz-develop/php-monad library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
wiz-develop / php-monad example snippets
use WizDevelop\PhpMonad\Option;
// 値がある場合(Some)
$some = Option::some("Hello, World!");
echo $some->unwrap(); // "Hello, World!"
// 値がない場合(None)
$none = Option::none();
// echo $none->unwrap(); // 例外が発生します
// 値の存在チェック
if ($some->isSome()) {
echo "値が存在します";
}
// デフォルト値の提供
echo $none->unwrapOr("Default Value"); // "Default Value"
// mapによる値の変換
$length = $some->map(fn($str) => strlen($str)); // Option::some(13)
// フィルタリング
$filtered = $some->filter(fn($str) => strlen($str) > 10); // Option::some("Hello, World!")
$filtered = $some->filter(fn($str) => strlen($str) > 20); // Option::none()
// 複数のOptionを連鎖
function findUser(string $id): Option {
// ...
}
function getUserPreferences(User $user): Option {
// ...
}
$preferences = findUser("123")
->flatMap(fn($user) => getUserPreferences($user));
use WizDevelop\PhpMonad\Result;
// 成功の場合(Ok)
$ok = Result::ok(42);
echo $ok->unwrap(); // 42
// 失敗の場合(Err)
$err = Result::err("Something went wrong");
// echo $err->unwrap(); // 例外が発生します
echo $err->unwrapErr(); // "Something went wrong"
// エラーチェック
if ($ok->isOk()) {
echo "処理は成功しました";
}
if ($err->isErr()) {
echo "エラーが発生しました";
}
// デフォルト値の提供
echo $err->unwrapOr(0); // 0
// mapによる値の変換
$doubled = $ok->map(fn($n) => $n * 2); // Result::ok(84)
// エラー値の変換
$newErr = $err->mapErr(fn($e) => "Error: " . $e); // Result::err("Error: Something went wrong")
// 複数のResultを連鎖
function fetchData(string $url): Result {
// ...
}
function processData($data): Result {
// ...
}
$processed = fetchData("https://api.example.com")
->flatMap(fn($data) => processData($data));
bash
composer