PHP code example of khalyomede / monad
1. Go to this page and download the library: Download khalyomede/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/ */
khalyomede / monad example snippets
use Khalyomede\Monad\Maybe;
function getFileContent(string $filePath): Maybe
{
$content = file_get_contents($filePath);
return $content === false ? Maybe::nothing() : Maybe::just($content);
}
// main
$content = getFileContent("data.txt")
->then(fn (string $data): string => $data)
->catch(fn (): string => "N/A");
echo $content;
use Khalyomede\Monad\Result;
function getUsers(): Result
{
$pdo = new PDO("sqlite::memory:");
$statement = $pdo->prepare("SELECT * FROM users");
if ($statement === false) {
$message = $pdo->errorInfo()[2];
return Result::error($message);
}
$result = $statement->execute();
if ($result === false) {
$message = $statement->errorInfo()[2];
return Result::error($message);
}
return Result::ok($statement->fetchAll());
}
// main
$users = getUsers()
->then(fn (array $records): array => $records)
->catch(function (string $error): array {
error_log($error);
return [];
});
use Khalyomede\Monad\Result;
function getFileContent(string $path): Result
{
$content = file_get_contents($path);
return $content === false ?
Result::error(new Exception("Cannot get content of file $path.")) :
Result::ok($content);
}
function saveFileContent(string $path, string $content): Result
{
$result = file_put_contents($path, $content);
return $result === false ?
Result::error(new Exception("Cannot write file content of file $path.")) :
Result::ok(true);
}
// main
$result = fileGetContent("composer.json")
->then(fn (string $content): Result => saveFileContent("composer.json.save", $content))
->then(fn (): string => "composer.json backup finished.")
->catch(fn (Exception $exception): string => $exception->getMessage());
echo $result . PHP_EOL;
bash
khalyomede@pc > php index.php
composer.json backup finished.
bash
khalyomede@pc > php index.php
Cannot get content of file composer.json.
bash
khalyomede@pc > php index.php
Cannot write file content of file composer.json.save.