1. Go to this page and download the library: Download brimmar/phpoption 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/ */
brimmar / phpoption example snippets
namespace Brimmar\PhpOption\Interfaces;
/**
* @template T
*/
interface Option
{
// ... (methods will be documented below)
}
use Brimmar\PhpOption\Some;
use Brimmar\PhpOption\None;
use Brimmar\PhpOption\Interfaces\Option;
class UserProfile
{
private $data = [];
public function setField(string $field, $value): void
{
$this->data[$field] = $value;
}
public function getField(string $field): Option
{
return isset($this->data[$field]) ? new Some($this->data[$field]) : new None();
}
public function getDisplayName(): string
{
return $this->getField('display_name')
->orElse(fn() => $this->getField('username'))
->unwrapOr('Anonymous');
}
public function getAge(): Option
{
return $this->getField('age')
->andThen(function($age) {
return is_numeric($age) && $age > 0 && $age < 120 ? new Some((int)$age) : new None();
});
}
}
$profile = new UserProfile();
$profile->setField('username', 'johndoe');
$profile->setField('age', '30');
echo $profile->getDisplayName(); // Output: johndoe
$age = $profile->getAge()
->map(fn($age) => "User is $age years old")
->unwrapOr("Age not provided or invalid");
echo $age; // Output: User is 30 years old
$email = $profile->getField('email')
->map(fn($email) => "Contact: $email")
->unwrapOr("No email provided");
echo $email; // Output: No email provided
use Brimmar\PhpOption\Some;
use Brimmar\PhpOption\None;
use Brimmar\PhpResult\Ok;
use Brimmar\PhpResult\Err;
class ConfigManager
{
private $configs = [];
public function getConfig(string $key): Option
{
return isset($this->configs[$key]) ? new Some($this->configs[$key]) : new None();
}
public function setConfig(string $key, $value): void
{
$this->configs[$key] = $value;
}
public function getRequiredConfig(string $key): Result
{
return $this->getConfig($key)
->ok()
->mapErr(fn() => "Required configuration '$key' is missing");
}
public function getDatabaseUrl(): Result
{
return $this->getRequiredConfig('database_url')
->andThen(function($url) {
$parsed = parse_url($url);
return isset($parsed['scheme'], $parsed['host'], $parsed['path'])
? new Ok($url)
: new Err("Invalid database URL format");
});
}
}
$manager = new ConfigManager();
$manager->setConfig('database_url', 'mysql://localhost/mydb');
$manager->setConfig('debug', true);
$debugMode = $manager->getConfig('debug')
->unwrapOr(false);
echo $debugMode ? "Debug mode is ON" : "Debug mode is OFF"; // Output: Debug mode is ON
$databaseUrl = $manager->getDatabaseUrl()
->map(fn($url) => "Connected to: $url")
->unwrapOr("Failed to connect to database");
echo $databaseUrl; // Output: Connected to: mysql://localhost/mydb
$apiKey = $manager->getRequiredConfig('api_key')
->match(
Ok: fn($key) => "API Key: $key",
Err: fn($error) => "Error: $error",
);
echo $apiKey; // Output: Error: Required configuration 'api_key' is missing
use Brimmar\PhpOption\Some;
use Brimmar\PhpOption\None;
use Brimmar\PhpOption\Interfaces\Option;
class Address
{
public function __construct(public string $street, public string $city, public string $country) {}
}
class User
{
public function __construct(public string $name, private ?Address $address = null) {}
public function getAddress(): Option
{
return $this->address ? new Some($this->address) : new None();
}
}
class UserRepository
{
private $users = [];
public function addUser(User $user): void
{
$this->users[] = $user;
}
public function findUserByName(string $name): Option
{
$user = array_values(array_filter($this->users, fn($u) => $u->name === $name))[0] ?? null;
return $user ? new Some($user) : new None();
}
}
$repo = new UserRepository();
$repo->addUser(new User("Alice", new Address("123 Main St", "Springfield", "USA")));
$repo->addUser(new User("Bob"));
function getUserCountry(UserRepository $repo, string $name): string
{
return $repo->findUserByName($name)
->andThen(fn($user) => $user->getAddress())
->map(fn($address) => $address->country)
->unwrapOr("Country not found");
}
echo getUserCountry($repo, "Alice"); // Output: USA
echo getUserCountry($repo, "Bob"); // Output: Country not found
echo getUserCountry($repo, "Charlie"); // Output: Country not found
$option = new Some(42);
echo $option->isSome(); // true
$option = new None();
echo $option->isSome(); // false
$option = new Some(42);
echo $option->isNone(); // false
$option = new None();
echo $option->isNone(); // true
$option = new Some(42);
foreach ($option->iter() as $value) {
echo $value; // 42
}
$option = new None();
foreach ($option->iter() as $value) {
// This block will never be executed
}
$option = new Some(42);
echo $option->unwrap(); // 42
$option = new None();
$option->unwrap(); // Throws RuntimeException
$option = new Some(42);
echo $option->expect("Value should be present"); // 42
$option = new None();
$option->expect("Value is