Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Functional Laravel Package

widmogrod/php-functional

Functional programming toolkit for PHP with immutable data structures, monads and typed abstractions. Includes Option/Either/Try, collections, pattern matching, and helpers for safer, composable code. Useful for DDD, CQRS and FP-style application architecture.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer: composer require widmogrod/php-functional. Start with the foundational types: Option for nullable values (avoiding null checks) and Either for explicit error handling. For example, replace a fragile getUserById($id) that might return null with Option::fromNullable($user) and safely chain operations: Option::fromNullable($user)->map(fn($u) => $u->getEmail())->getOrElse('no-email@example.com'). For error-prone operations (e.g., parsing, external API calls), prefer Either over exceptions in business logic:

$result = Either::tryCatch(fn() => json_decode($input, true))
    ->mapLeft(fn($e) => "Invalid JSON: " . $e->getMessage());

Check the src/ folder for core classes (Option, Either, Collection) and use PSR-18/HTTP client integrations if present.

Implementation Patterns

  • Data Transformation Pipelines: Chain Collection::from($items)->map()->filter()->reduce() for domain-wide data processing (e.g., transforming order payloads without intermediate arrays).
  • Explicit Error Propagation: Use Either to model validation failures in DTOs or use cases—e.g., validateUserInput($data)->flatMap(fn($input) => createUser($input)) where validateUserInput() returns Either<Error, ValidatedInput>.
  • Safe Side Effects: Wrap impure operations (DB calls, file system) in Either::tryCatch() at the edge, then compose pure functions upstream.
  • Pattern Matching via match or matchWith: Replace nested if/else or switch with declarative branching:
Option::just($user)->match(
    fn($u) => "User: {$u->getName()}",
    fn() => "Guest"
);
  • Dependency Injection: Pass pure functions (e.g., isEligible::class) into services instead of hardcoding logic, enabling easier unit testing.

Gotchas and Tips

  • Immutability Enforcement: All functional types (Option, Either, Collection) are immutable—calls like map() return new instances. Accidentally reusing variables leads to stale values; use strict typing (declare(strict_types=1)) and IDE support to catch this.
  • Type Inference Limitations: PHP’s type inference may struggle with deeply nested Either<Error, Either<Error, T>>. Prefer flattening with flatMap or introduce small domain-specific helpers (e.g., ValidationResult::success($data)).
  • Collection Performance: Collection uses lazy evaluation internally; avoid toArray() in tight loops—use each() or reduce() for streaming.
  • Error Handling Strategy: Don’t convert every exception to Either; reserve it for expected errors (validation, domain rules). Reserve exceptions for unexpected failures (database down, programming bugs).
  • Testing Tip: Write unit tests by comparing Option/Either values, not instances. Use ->getOrThrow() only in tests for clarity, not production code.
  • Extension Point: Create your own Validation or Result wrapper types by extending Either and implementing domain-specific combinators (e.g., andThenValidateEmail()).
  • Debugging: Use peek() in chains to log intermediate values without breaking composition: Collection::from($items)->map(...)->peek(fn($x) => logger()->info('Got item', $x))->reduce(...).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport