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

Pact Php Laravel Package

pact-foundation/pact-php

PHP implementation of the Pact consumer-driven contract testing framework. Define contracts between services, run provider verification, and integrate with PHPUnit/CI to prevent breaking API changes. Supports HTTP interactions, mock servers, and Pact Broker workflows.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Consumer-Driven Contracts (CDC) Alignment: The package aligns well with microservices, API-first architectures, and continuous delivery pipelines where consumer-provider interactions must be explicitly defined and validated. Ideal for teams practicing contract testing to prevent integration failures.
  • Laravel Compatibility: As a PHP package, it integrates natively with Laravel’s HTTP layer (e.g., Illuminate\Http\Client, Route::get(), etc.) and can mock external services (e.g., APIs, queues) during unit/integration tests.
  • Testing Pyramid Placement: Best suited for integration tests (not unit tests) to verify API contracts between services. Complements Laravel’s built-in testing tools (PHPUnit, Pest) but operates at a higher level of abstraction.

Integration Feasibility

  • Mock Service Provider: The package allows consumers to define expectations (e.g., request/response pairs) and generate a mock server for testing. This can replace Laravel’s Http::fake() for cross-service interactions.
  • Provider Verification: Service providers can verify interactions against Pact contracts, ensuring backward compatibility during refactoring or updates.
  • DSL Flexibility: The Domain-Specific Language (DSL) supports:
    • Request/response matching (headers, body, status codes).
    • State management (e.g., given(), willRespondWith() for stateful APIs).
    • Asynchronous interactions (queues, events) via Laravel’s Bus or Events.
  • Laravel-Specific Considerations:
    • Service Container: Pact’s mock server can be bootstrapped as a Laravel service provider or used in test suites.
    • Artisan Commands: Provider verification can be wrapped in a custom artisan pact:verify command.
    • Publishing Config: Contracts can be stored in config/pact.php or versioned alongside API specs (OpenAPI/Swagger).

Technical Risk

Risk Area Mitigation Strategy
Test Flakiness Pact’s strict matching may expose overly rigid contracts. Use generous matching (e.g., regex, wildcards) where appropriate.
Performance Overhead Mock servers add latency. Use parallel test execution (e.g., Pest’s --parallel) and cache contracts to avoid regeneration.
Tooling Ecosystem Limited Laravel-specific docs. Requires familiarity with Pact’s broader ecosystem (e.g., Pact Broker for contract storage).
State Management Complex state transitions (e.g., multi-step workflows) may need custom providers or Laravel’s DatabaseTransactions.
Version Skew Contracts must align with API versions. Use semantic versioning for contracts and automate version checks in CI.

Key Questions

  1. Contract Storage:
    • Will contracts be stored in version control (e.g., Git) or a Pact Broker? How will versioning align with API releases?
  2. Testing Strategy:
    • Should Pact replace Laravel’s Http::fake() entirely, or supplement it for cross-service tests?
  3. CI/CD Integration:
    • How will Pact verification fit into the deploy pipeline (e.g., pre-merge, post-deploy)?
  4. Provider Complexity:
    • Are providers stateless (REST) or stateful (e.g., GraphQL mutations, queues)? Does Pact support the required interaction types?
  5. Team Adoption:
    • What training or documentation is needed for developers to write/maintain Pact contracts?
  6. Mock Granularity:
    • Should contracts mock entire services or specific endpoints? How will this scale with API growth?

Integration Approach

Stack Fit

  • Laravel Core:
    • HTTP Layer: Pact’s mock server can intercept Http::get(), Http::post(), etc., replacing Laravel’s Http::fake() for external calls.
    • Routing: Use Route::get() with Pact’s DSL to define expected routes in tests.
    • Service Providers: Bootstrap Pact’s mock server in App\Providers\PactServiceProvider or test suites.
  • Testing Tools:
    • PHPUnit/Pest: Pact tests can run alongside Laravel’s test suite. Use @pact annotations or custom test traits.
    • Dusk/BrowserKit: Not directly applicable, but Pact can mock APIs called by frontend tests.
  • Async Support:
    • Queues: Mock Illuminate\Queue interactions using Pact’s async DSL.
    • Events: Verify event publishing/consumption with Pact’s interaction matching.

Migration Path

  1. Pilot Phase:
    • Start with one high-risk API (e.g., payment service) to define and test contracts.
    • Replace existing Http::fake() calls with Pact for that service.
  2. Tooling Setup:
    • Install pact-foundation/pact-php via Composer.
    • Configure Pact’s mock service in phpunit.xml or pest.php.
    • Example:
      // config/pact.php
      return [
          'mock_service' => [
              'host' => 'localhost',
              'port' => 1234,
          ],
          'provider' => [
              'name' => 'laravel-service',
              'broker' => env('PACT_BROKER_URL'),
          ],
      ];
      
  3. Contract Definition:
    • Write Pact contracts in consumer tests (e.g., tests/Features/Pact/ApiConsumerTest.php).
    • Example:
      $pact = new Consumer('laravel-consumer', 'v1');
      $pact->given('a user exists')
           ->uponReceiving('a GET request to /users/{id}')
           ->withRequest('GET', '/users/123')
           ->willRespondWith(200, ['id' => 123, 'name' => 'John Doe']);
      
  4. Provider Verification:
    • Add a custom Artisan command to verify contracts against the live provider:
      // app/Console/Commands/VerifyPact.php
      use Pact\Verifier\Verifier;
      
      public function handle() {
          $verifier = new Verifier();
          $verifier->verifyProvider(
              new Provider('laravel-service'),
              ['tests/Features/Pact/pacts']
          );
      }
      
    • Run in CI:
      php artisan pact:verify
      

Compatibility

  • Laravel Versions:
    • Tested with Laravel 10+ (PHP 8.1+). May require adjustments for older versions.
  • PHP Extensions:
    • No hard dependencies, but cURL is needed for HTTP interactions.
  • Pact Broker:
    • Optional but recommended for contract versioning and sharing. Use the Pact Broker for teams with multiple providers/consumers.
  • CI/CD:
    • Integrate with GitHub Actions, GitLab CI, or CircleCI to run Pact verification on PRs.

Sequencing

  1. Consumer-Side:
    • Define contracts before implementing the consumer logic (TDD-style).
    • Order: Contract DefinitionConsumer ImplementationContract Verification.
  2. Provider-Side:
    • Implement provider logic after contracts are defined.
    • Order: Contract Definition (by consumer)Provider ImplementationPact Verification.
  3. CI Pipeline:
    • Consumer: Verify contracts pass during unit/integration tests.
    • Provider: Run pact:verify in a separate CI job (e.g., after merge to main).

Operational Impact

Maintenance

  • Contract Updates:
    • Contracts must be updated proactively when APIs change. Use semantic versioning (e.g., v1, v2) to manage breaking changes.
    • Automate contract generation from OpenAPI/Swagger if APIs are documented there.
  • Deprecation:
    • Sunset old contracts via Pact Broker tags or CI checks.
    • Example: Add a deprecated: true flag to contracts in the Broker.
  • Tooling:
    • Pact CLI can help manage contracts:
      pact-cli publish tests/Features/Pact/pacts --broker-base-url=$PACT_BROKER_URL
      

Support

  • Debugging:
    • Pact provides detailed diffs when contracts fail. Example:
      Expected: { "status": "success" }
      Actual:   { "status": "error", "message": "..." }
      
    • Use --verbose flag for mock server logs.
  • Onboarding:
    • Document contract ownership (e.g., "API team owns /users contract").
    • Create a template for Pact tests (e.g., tests/Features/Pact/TemplateTest.php).
  • **Escal
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui