Weave 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

Either Or Both Laravel Package

php-standard-library/either-or-both

A three-variant disjoint union type for PHP. EitherOrBoth models values that may be present on the left, the right, or both sides at once, giving you a type-safe way to express partial successes, asymmetric results, and paired data without nullable workarounds.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: The EitherOrBoth type is a three-state disjoint union (Left/Right/Both), which is ideal for modeling scenarios where a value can exist in one, the other, or both states simultaneously. This is particularly useful in:
    • Asynchronous workflows (e.g., API responses with partial success/failure).
    • Data validation (e.g., form submissions where some fields pass but others fail).
    • State machines (e.g., transitions where multiple conditions must be evaluated).
    • Event sourcing/CQRS (e.g., handling dual-write scenarios where a command may affect two aggregates).
  • Laravel Synergy: Laravel’s ecosystem (e.g., Illuminate\Support\Collection, Illuminate\Validation\Validator) often deals with partial data states (e.g., validation errors mixed with successful fields). This package could reduce boilerplate for handling such cases.
  • Type Safety: PHP 8.2+ supports union types, but this package provides a structured, immutable way to handle three-state logic, which is harder to model natively.

Integration Feasibility

  • Low Coupling: The package is standalone (no Laravel-specific dependencies) and can be integrated via Composer (php-standard-library/either-or-both).
  • PHP Version Compatibility:
    • Requires PHP 8.1+ (due to named arguments and enums).
    • Laravel 10.x+ (PHP 8.1+) is fully compatible; older versions (e.g., Laravel 9) may need polyfills or manual adjustments.
  • Testing: The package includes PHPUnit tests, but a TPM should validate edge cases (e.g., nested EitherOrBoth types, serialization/deserialization).

Technical Risk

Risk Area Assessment Mitigation Strategy
Learning Curve Developers unfamiliar with disjoint unions may need training. Write internal docs with Laravel-specific examples (e.g., validation, API responses).
Performance Overhead Immutable objects may have slight memory overhead vs. primitive checks. Benchmark in critical paths; prefer for complex logic, not simple flags.
Type System Quirks PHP’s dynamic nature may lead to runtime mismatches if not used strictly. Enforce strict typing in CI (e.g., phpstan).
Lack of Adoption Low stars/dependents may indicate niche use or instability. Pilot in a non-critical module; monitor for updates.
Serialization Custom serialization may be needed for APIs/database storage. Extend with JsonSerializable or Laravel’s Serializable trait.

Key Questions for the TPM

  1. Where is the pain point?
    • Is this replacing ad-hoc array/null checks, or solving a new problem (e.g., dual-write consistency)?
  2. What’s the adoption path?
    • Will this be opt-in (gradual) or mandatory (big-bang)?
  3. How will we test it?
    • Are there existing tests for partial-state logic (e.g., validation, async jobs)?
  4. What’s the fallback?
    • If adoption fails, what’s the revert plan (e.g., custom classes, stdClass hacks)?
  5. Who owns the standard?
    • Will the team enforce usage, or is this a "best practice" suggestion?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Validation: Replace manual Validator::errors() + Validator::passes() checks with EitherOrBoth<ValidationErrors, ValidData>.
    • API Responses: Standardize partial failures (e.g., Both for mixed success/error responses).
    • Queues/Jobs: Model dual-write outcomes (e.g., Both if a job affects two databases).
    • Form Requests: Simplify authorize() + validate() logic into a single EitherOrBoth return.
  • Third-Party Libraries:
    • Works with Symfony Components (e.g., HttpFoundation responses).
    • Compatible with Doctrine (for DTOs with optional fields).
  • Frontend: Can be serialized to JSON for API consumers (e.g., { "status": "both", "left": {...}, "right": {...} }).

Migration Path

  1. Pilot Phase:
    • Start with one high-impact module (e.g., a complex validation rule or async job).
    • Replace existing array/null logic with EitherOrBoth.
  2. Incremental Replacement:
    • Use PHPStan to detect unsafe type usage.
    • Gradually replace if-else chains with match expressions (PHP 8.2+).
  3. API Contracts:
    • Update OpenAPI/Swagger specs to document the EitherOrBoth response shape.
  4. Database Layer:
    • If storing Both states, consider JSON columns or separate tables for left/right values.

Compatibility

Component Compatibility Notes
PHP 8.1+ Required for enums and named arguments.
Laravel 10.x+ Full support; older versions may need polyfills.
Composer Install via composer require php-standard-library/either-or-both.
IDE Support Modern IDEs (PHPStorm, VSCode) will autocomplete Left/Right/Both variants.
Legacy Code May require adapter classes to bridge old array logic to EitherOrBoth.

Sequencing

  1. Phase 1: Core Integration (2-4 weeks)
    • Add to composer.json.
    • Write wrapper classes for common use cases (e.g., ValidationEitherOrBoth).
  2. Phase 2: Validation Layer (1-2 weeks)
    • Replace custom validation logic with EitherOrBoth-based responses.
  3. Phase 3: API Responses (2-3 weeks)
    • Standardize API contracts for partial failures/successes.
  4. Phase 4: Async Workflows (1-2 weeks)
    • Apply to queues/jobs for dual-write scenarios.
  5. Phase 5: Documentation (Ongoing)
    • Publish internal guides and examples.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Immutable types cut down on manual state management.
    • Self-Documenting: EitherOrBoth makes code intent clearer than nested if checks.
    • Consistent Error Handling: Standardizes partial failures across the codebase.
  • Cons:
    • New Abstraction Layer: Developers must learn the pattern.
    • Debugging Complexity: Nested EitherOrBoth types may require deeper inspection.
  • Tooling:
    • PHPStan: Enforce strict usage.
    • Custom Snippets: IDE templates for match expressions.

Support

  • Developer Onboarding:
    • Requires 1-2 hours of training per developer (focus on match vs. if-else).
    • Provide cheat sheets for common patterns (e.g., validation, API responses).
  • Common Issues:
    • Misuse of Both: Ensure teams don’t overuse it for unrelated data.
    • Serialization Pitfalls: Document JSON/API serialization rules.
  • Support Channels:
    • Internal Wiki: Document use cases and anti-patterns.
    • Pair Programming: For complex integrations (e.g., async jobs).

Scaling

  • Performance:
    • Minimal Overhead: Immutable objects have predictable memory usage.
    • Caching: Works well with Laravel’s cache (serialize/deserialize via JsonSerializable).
  • Horizontal Scaling:
    • No impact on database or external services; purely a logic layer.
  • Team Adoption:
    • Early Adopters: Start with backend teams (validation, API).
    • Gradual Rollout: Avoid forcing frontend teams until API contracts stabilize.

Failure Modes

Failure Scenario Impact Mitigation
Incorrect EitherOrBoth usage Runtime errors or silent bugs. PHPStan + CI checks for invalid variants.
Serialization issues API/database corruption. Enforce JsonSerializable or custom serializers.
Over-engineering Unnecessary complexity. Limit scope to clear pain points (e.g., validation, async jobs).
Lack of adoption Package becomes dead code. Tie to critical features (e.g., new validation system).
PHP Version Downgrade Breaks if PHP <8.1 is required. Document version constraints; avoid in legacy projects.

Ramp-Up

  • **Training
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.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log