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

Clock Laravel Package

eventsauce/clock

Simple clock abstraction for PHP. Use SystemClock in production and TestClock in tests to control time deterministically. Get now() as DateTimeImmutable, access timeZone(), move time forward, tick to system time, or fixate to a specific moment.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven & CQRS Alignment: The eventsauce/clock package is designed to decouple time consumption from business logic, making it a strong fit for event-sourced or CQRS architectures where deterministic replay of events is critical. It abstracts time handling, allowing for:
    • Time-travel debugging (e.g., replaying events with a fixed clock).
    • Testing (mocking time for predictable event processing).
    • Eventual consistency (e.g., adjusting timestamps for delayed processing).
  • Domain-Driven Design (DDD) Compatibility: Aligns well with bounded contexts where time is a domain concern (e.g., financial systems, workflows with deadlines).
  • Microservices: Useful in distributed systems where clocks may be unsynchronized (e.g., compensating for clock skew in event sourcing).

Integration Feasibility

  • PHP/Laravel Ecosystem: Seamlessly integrates with Laravel’s event system (e.g., Illuminate\Events\Dispatcher) and queues (e.g., Illuminate\Queue). Can replace now() calls with a Clock instance for consistency.
  • Event Store Compatibility: Works with event-sourced packages like spatie/laravel-event-sourcing or eventSaucePHP/event-store.
  • Middleware/Service Provider: Can be injected via Laravel’s service container (e.g., binding ClockInterface to a concrete implementation).
  • Database-Agnostic: No direct DB dependencies, but requires alignment with how timestamps are stored/retrieved (e.g., created_at in Laravel models).

Technical Risk

  • Time Skew in Distributed Systems: If not configured correctly, clock adjustments could lead to inconsistent event ordering or race conditions (e.g., two services processing events with different clocks).
  • Testing Overhead: While the package simplifies time mocking, complex event replays may require additional tooling (e.g., eventsauce/event-store for snapshot testing).
  • Laravel-Specific Quirks:
    • Carbon Integration: Laravel relies heavily on Carbon for dates. The package may require adapters to ensure compatibility (e.g., converting Clock\DateTime to Carbon instances).
    • Queue Workers: If using Laravel queues, workers must be aware of the clock to avoid timestamp mismatches (e.g., delayed jobs).
  • Performance Impact: Minimal, but freezing time (e.g., for testing) could introduce subtle bugs if not handled carefully (e.g., timeouts, retries).

Key Questions

  1. Use Case Clarity:
    • Is this for event replay, testing, or time-adjustable workflows? The package’s utility varies by need.
    • Does the system require strict event ordering (e.g., financial transactions) where clock precision is critical?
  2. Clock Synchronization:
    • How will clocks be synchronized across services? (e.g., NTP, leader election, or a central clock service).
  3. Laravel-Specific Adaptations:
    • Will the package replace now() globally, or only in specific contexts (e.g., event publishing)?
    • How will Carbon instances interact with Clock\DateTime? (e.g., via a facade or adapter).
  4. Failure Modes:
    • What happens if a clock is manually adjusted during production? (e.g., for debugging).
    • How are time-based validations (e.g., "event must be within 1 hour") handled?
  5. Tooling:
    • Are there plans to integrate with Laravel Horizon (for queue monitoring) or Laravel Telescope (for debugging)?

Integration Approach

Stack Fit

  • Core Fit: Ideal for Laravel applications using:
    • Event Sourcing (e.g., spatie/laravel-event-sourcing).
    • CQRS (e.g., laravel-cqrs packages).
    • Domain Events (e.g., laravel-domain-events).
  • Non-Fit: Less useful for:
    • Simple CRUD apps without event-driven logic.
    • Real-time systems where clock precision is managed externally (e.g., WebSockets with server-side time).

Migration Path

  1. Phase 1: Testing Integration
    • Replace now() with Clock in unit tests (e.g., mocking time for event publishing).
    • Example:
      $clock = new FixedClock(new \DateTime('2023-01-01'));
      app()->bind(ClockInterface::class, fn() => $clock);
      
  2. Phase 2: Event Layer Adoption
    • Inject ClockInterface into event listeners/publishers.
    • Example:
      public function handle(ExampleEvent $event, ClockInterface $clock) {
          $now = $clock->now(); // Use clock instead of now()
      }
      
  3. Phase 3: Event Store Integration
    • Configure the event store to use the clock (e.g., EventSaucePHP/event-store).
    • Example:
      $eventStore = new EventStore(
          new Clock(), // Use the package's clock
          new PdoStreamRepository($pdo)
      );
      
  4. Phase 4: Queue Workers
    • Ensure queue workers (e.g., Laravel Horizon) use the clock for time-sensitive logic (e.g., delayed jobs).

Compatibility

  • Laravel Versions: Compatible with Laravel 8+ (PHP 8.0+). May require minor adjustments for older versions.
  • Event Packages:
    • Works with Laravel’s built-in events but shines with third-party event-sourcing packages.
    • Potential conflict with packages that hardcode now() (e.g., some audit log packages).
  • Database:
    • No direct DB changes needed, but timestamp fields must align with the clock’s output (e.g., created_at in Laravel models).

Sequencing

  1. Start with Isolated Components:
    • Begin with event publishing/listeners before expanding to queues or databases.
  2. Test Clock Behavior:
    • Validate event replay and time adjustments in staging before production.
  3. Gradual Rollout:
    • Use feature flags to toggle clock usage in different services.
  4. Monitor Time-Dependent Logic:
    • Watch for time-based failures (e.g., expired tokens, missed deadlines) during adoption.

Operational Impact

Maintenance

  • Pros:
    • Reduced Flakiness: Time mocking in tests becomes deterministic.
    • Debugging: Easier to replay events for debugging (e.g., "Why did this order fail?").
  • Cons:
    • Additional Abstraction: Requires maintaining clock configurations across services.
    • Testing Complexity: Event replays may need snapshot testing (e.g., eventsauce/event-store snapshots).

Support

  • Debugging:
    • Clock Mismatches: Support teams must verify clocks are synchronized (e.g., "Why is Service A’s clock 5 minutes ahead?").
    • Time-Based Bugs: Issues like "events processed out of order" become harder to diagnose without clock awareness.
  • Documentation:
    • Must document clock usage in each service (e.g., "This service uses a fixed clock for testing").
    • Runbooks for clock adjustments (e.g., "How to reset a frozen clock in production").

Scaling

  • Performance:
    • Minimal overhead, but freezing time (e.g., for testing) could impact performance in long-running processes.
  • Distributed Systems:
    • Clock Skew: In multi-service setups, ensure clocks are synchronized (e.g., via NTP or a central clock service).
    • Eventual Consistency: Time adjustments may require compensation events to maintain consistency.
  • Horizontal Scaling:
    • Stateless clocks (e.g., FixedClock) scale well, but shared clocks (e.g., SystemClock) must be managed carefully.

Failure Modes

Failure Scenario Impact Mitigation
Clock desynchronization Events processed out of order Use a central clock service or NTP.
Clock frozen in production Time-based logic fails (e.g., retries) Implement circuit breakers for clock adjustments.
Event replay with incorrect clock Inconsistent state Use snapshot testing for critical replays.
Package version incompatibility Breaking changes in API Pin versions in composer.json.
Carbon/Clock integration bugs DateTime conversion errors Write adapters for Carbon ↔ Clock\DateTime.

Ramp-Up

  • Developer Onboarding:
    • Training: Teach teams how to inject clocks and mock time in tests.
    • **
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