phonad / core
Building blocks for functional programming in PHP
Fund package maintenance!
atomicptr
Buy Me A Coffee
Installs: 1
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/phonad/core
Requires (Dev)
- pestphp/pest: ^4.2
- phpstan/phpstan: ^2.1
This package is auto-updated.
Last update: 2025-12-18 18:39:40 UTC
README
Building blocks for functional programming in PHP, inspired by Haskell.
Note: This is an experiment to play around with Functional Programming in PHP
Install
Install via composer:
$ composer require phonad/core
Data Structures
Maybe
Handles optional values without null.
<?php use Phonad\Core\Data\Maybe; $val = Maybe::of(10) ->map(fn($n) => $n * 2) ->orElse(0); // 20
Either
Error handling: Right for success, Left for failure.
<?php use Phonad\Core\Data\Either; $res = Either::Right(10) ->flatMap(fn($n) => $n > 5 ? Either::Right($n) : Either::Left("Too small")) ->either(fn($err) => "Error: $err", fn($val) => "Value: $val");
ImmutableList
Immutable linked list (PDS).
<?php use Phonad\Core\Data\ImmutableList; $list = ImmutableList::from([1, 2, 3]) ->cons(0) ->filter(fn($n) => $n > 0); // [1, 2, 3]
Effects
Reader
Dependency injection via environment.
<?php use Phonad\Core\Effect\Reader; $logic = Reader::ask()->map(fn($env) => "Env is: " . $env['mode']); echo $logic->run(['mode' => 'production']);
Writer
Pure logging alongside values.
<?php use Phonad\Core\Effect\Writer; [$val, $logs] = Writer::of(10) ->flatMap(fn($n) => Writer::of($n + 1, ["Incremented"])) ->run();
IO
Lazy side effects.
<?php use Phonad\Core\Effect\IO; // Wrap the effect into the `IO` monad $sayHello = fn(string $name) => IO::make(function () use ($name) { echo "Hello, $name!"; }); // Chain the logic (nothing actually happens yet) $program = IO::of('world') ->map('strtoupper') ->flatMap(fn($name) => $sayHello($name)); // FIRE! $program->run(); // Outputs: Hello, WORLD!
License
MIT