PHP code example of bosunski / results

1. Go to this page and download the library: Download bosunski/results 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/ */

    

bosunski / results example snippets




use function Bosunski\Results\Option;

$some = Option('value'); // Some
$none = Option(null); // None



use function Bosunski\Results\Result;

$ok = Result('value'); // Ok
$err = Result(new Exception('error')); // Err



use function Bosunski\Results\Option;
use function Bosunski\Results\Result;

// Options
$some = Option('value'); // Some
$none = Option(null); // None

// Results
$ok = Result('value'); // Ok
$err = Result(new Exception('error')); // Err



use Bosunski\Results\Option as OptionInterface;
use function Bosunski\Results\Option;

function findUserById($id): OptionInterface {
    // Assume getUserFromDatabase is a function that returns a User object if found, null otherwise
    $user = getUserFromDatabase($id);
    
    return Option($user);
}

$userOption = findUserById(123);

// We can then handle the optional value using the methods provided by the Option type
if ($userOption->isSome()) {
    $user = $userOption->unwrap();
    // Do something with the user
} else {
    // Handle the case where no user was found
}

// You can also do this
$user = $userOption->unwrap() // Throws error if null



use Bosunski\Results\Result\Result as ResultInterface;
use function Bosunski\Results\Result;

function divide(int $numerator, int $denominator): ResultInterface {
    if ($denominator == 0) {
        return Err(new Exception("Cannot divide by zero"));
    } else {
        return Ok($numerator / $denominator);
    }
}

$result = divide(10, 0);

// We can then handle the result using the methods provided by the Result type
if ($result->isOk()) {
    $value = $result->unwrap();
    // Do something with the value
} else {
    $error = $result->unwrapErr();
    // Handle the error
}

// You can also do this
$user = $result->unwrap() // Throws error if an error is present



use function Bosunski\Results\wrap;

function mightThrowException(): int {
    if (rand(0, 1) === 1) {
        throw new Exception('An error occurred');
    }

    return 42;
}

$result = wrap(mightThrowException(...));

if ($result->isOk()) {
    echo "Success: " . $result->unwrap();
} else {
    echo "Error: " . $result->unwrapErr()->getMessage();
}