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

Type Laravel Package

typhoon/type

Typhoon Type provides an object abstraction over PHP’s modern type system for building tools that understand complex types. Define, print (stringify), and work with array shapes, object types, non-empty lists, and more in a consistent API.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strong alignment with Laravel’s type safety goals: Typhoon Type provides a runtime type system that complements PHP’s static typing, enabling runtime validation, serialization, and deserialization—critical for APIs, form handling, and data contracts in Laravel.
  • Domain-Driven Design (DDD) & CQRS fit: Ideal for command/query validation (e.g., ensuring API payloads match expected schemas) and event sourcing (validating event payloads).
  • Alternative to spatie/laravel-data: Offers more granular control over type constraints (e.g., nonEmptyStringT, intRangeT(-5, 6)) and PHPDoc compatibility, making it suitable for self-documenting APIs.
  • Integration with Laravel’s existing tooling:
    • Form Request Validation: Replace manual Validator rules with type-driven validation.
    • API Contracts: Define OpenAPI/Swagger schemas programmatically via stringify().
    • Eloquent Models: Enforce type-safe relationships (e.g., objectT(User::class) for belongsTo).

Integration Feasibility

  • Low friction for Laravel:
    • Composer install: composer require typhoon/type (no Laravel-specific dependencies).
    • Service Provider: Register a global type mapper (e.g., Typhoon\Type\Mapper) for request/response transformation.
    • Middleware: Validate incoming requests via Typhoon\Type\Validator.
  • PHP 8.1+ required: Laravel 9+ (PHP 8.1+) is fully compatible; Laravel 8.x may need minor adjustments.
  • No ORM bloat: Unlike some packages, this focuses purely on types, avoiding coupling with Eloquent/Query Builder.

Technical Risk

Risk Area Mitigation Strategy
Performance Overhead Benchmark Mapper::map() vs. manual validation; cache compiled types if needed.
BC Breaks Version pinning (^0.8) and feature flags for breaking changes (e.g., invariantT).
Learning Curve Document common patterns (e.g., "How to validate a Laravel Form Request").
Runtime vs. Static Use alongside PHPStan for dual-layer validation (static + runtime).
Limited Adoption Build Laravel-specific wrappers (e.g., Typhoon\Laravel\TypeValidator).

Key Questions

  1. How will this integrate with Laravel’s existing validation pipeline (e.g., Illuminate\Validation\Validator)?
    • Solution: Create a TyphoonValidator extending Laravel’s Validator to bridge the gap.
  2. Can we leverage this for API responses (e.g., JSON:API, GraphQL)?
    • Solution: Use stringify() to generate OpenAPI schemas dynamically.
  3. What’s the impact on legacy code (e.g., dynamic arrays, loose typing)?
    • Solution: Start with critical paths (e.g., API endpoints) and gradually adopt.
  4. How does this interact with Laravel’s service container?
    • Solution: Bind Typhoon\Type\Mapper as a singleton for global access.
  5. Is there a way to auto-generate PHPDoc types from Typhoon types?
    • Solution: Extend Stringify to output PHPDoc-compatible strings for IDE hints.

Integration Approach

Stack Fit

Laravel Component Typhoon Type Use Case
Form Requests Replace rules() with Typhoon\Type\Validator for type-safe validation.
API Resources Define response contracts (e.g., arrayShapeT(['data' => objectT(UserResource::class)])).
Eloquent Models Enforce type-safe relationships (e.g., objectT(User::class) for belongsTo).
Events Validate event payloads (e.g., objectShapeT(['user_id' => intT()])).
Middleware Add Typhoon\Type\ValidateRequest middleware for global type enforcement.
Testing Use Typhoon\Type\Assert in PHPUnit to validate test data.
OpenAPI/Swagger Generate schemas via stringify() for auto-documented APIs.

Migration Path

  1. Phase 1: Validation Layer
    • Replace manual Validator rules with Typhoon\Type\Validator.
    • Example:
      use Typhoon\Type\Validator;
      
      $validator = new Validator([
          'name' => nonEmptyStringT(),
          'age'  => intRangeT(18, 120),
      ]);
      
  2. Phase 2: API Contracts
    • Define request/response types in a central ApiTypes class.
    • Example:
      final class ApiTypes {
          public static function UserResponse(): arrayShapeT {
              return arrayShapeT([
                  'id'    => intT(),
                  'email' => nonEmptyStringT(),
              ]);
          }
      }
      
  3. Phase 3: Eloquent Integration
    • Use objectT() for type-safe model relationships.
    • Example:
      class Post extends Model {
          public function user(): BelongsTo {
              return $this->belongsTo(User::class)
                  ->setTypeHint(objectT(User::class)); // Enforce type safety
          }
      }
      
  4. Phase 4: Testing & Documentation
    • Replace assertArrayHasKey() with Typhoon\Type\Assert.
    • Generate PHPDoc types from stringify() for IDE support.

Compatibility

  • Laravel 9+ (PHP 8.1+): Full compatibility.
  • Laravel 8.x (PHP 8.0): Minor adjustments needed (e.g., named arguments).
  • Legacy Code: Use optional typing (e.g., nullOrT(arrayT())) for gradual adoption.
  • Third-Party Packages:
    • spatie/laravel-data: Can coexist but may require adapter layer.
    • NunoMaduro/collision: Use for static analysis alongside Typhoon’s runtime checks.

Sequencing

  1. Start with API endpoints (highest ROI for type safety).
  2. Move to Form Requests (replace rules()).
  3. Adopt in Eloquent (type-safe relationships).
  4. Extend to Events/Jobs (ensure payload integrity).
  5. Finalize with Testing (auto-generated assertions).

Operational Impact

Maintenance

  • Pros:
    • Reduced boilerplate: Replace repetitive Validator rules with declarative types.
    • Centralized type definitions: Single source of truth for API contracts.
    • IDE-friendly: PHPDoc generation via stringify() improves developer experience.
  • Cons:
    • Runtime validation overhead: Benchmark and optimize critical paths (e.g., caching compiled types).
    • Type evolution: Requires backward-compatible updates when adding new constraints (e.g., intRangeT).

Support

  • Debugging:
    • Clear error messages: Typhoon provides descriptive type mismatch errors (e.g., "Expected non-empty-string, got ''").
    • Stack traces: Integrate with Laravel’s exception handler for user-friendly errors.
  • Troubleshooting:
    • Common pitfalls:
      • Forgetting nonEmptyStringT vs. stringT.
      • Misusing arrayShapeT vs. arrayT.
    • Solution: Document anti-patterns in team guidelines.

Scaling

  • Performance:
    • Caching: Cache compiled types (e.g., arrayShapeT) in Laravel’s cache.
    • Lazy loading: Defer type validation until necessary (e.g., only validate on save()).
  • Team Adoption:
    • Onboarding: Provide cheat sheets for common type patterns.
    • Pair programming: Demo Typhoon + Laravel integration in team sessions.
  • Microservices:
    • Contract-first: Define inter-service types (e.g., arrayShapeT(['user' => objectT(UserDTO::class)])).
    • Schema registry: Store types in database/Redis for dynamic validation.

Failure Modes

Scenario Mitigation
Invalid API payload Return 422 Unprocessable Entity with Typhoon error details.
Type mismatch in DB Use Typhoon\Type\Assert in model observers to catch inconsistencies.
Performance regression Profile Mapper::map()
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor