PHP code example of tekord / php-result

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

    

tekord / php-result example snippets


class ErrorInfo {
    public $code;
    public $message;
    public $context;

    public function __construct($code, $message, $context = []) {
        $this->code = $code;
        $this->message = $message;
        $this->context = $context;
    }
}

function createOrder(User $user, $products): Result {
    if (!$user->isVerified())
        return Result::fail(
            new ErrorInfo("unverified_user", "Unverified users are not allowed to order", [
                'user' => $user
            ])
        );
        
    if ($user->hasDebts())
        return Result::fail(
            new ErrorInfo("user_has_debts", "Users with debts are not allowed to order new items", [
                'user' => $user
            ])
        );
        
    if ($products->isEmpty())
        return Result::fail(
            new ErrorInfo("no_products", "Products cannot be empty")
        );
  
    // Create a new order here...
    
    return Result::success($newOrder);
}

// ...

$createOrderResult = createOrder($user, $productsFromCart);

// This will throw a panic exception if the result contains an error
$newOrder = $createOrderResult->unwrap();
   
// - OR -

// You can check if the result is OK and make a decision on it
if ($createOrderResult->isOk()) {
    $newOrder = $createOrderResult->ok;
    
    // ...
}
else {
    throw new DomainException($createOrderResult->error->message);
}

// - OR -

// Get a default value if the result contains an error
$newOrder = $createOrderResult->unwrapOrDefault(new Order());

/**
 * @tempate OkType
 * @tempate ErrorType
 *
 * @extends Result<OkType, ErrorType>
 */
class CustomResult extends Result {
    static $panicExceptionClass = DomainException::class;
}
bash
composer