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

lcobucci/clock

Clock abstraction for PHP to decouple your code from DateTimeImmutable instantiation. Depend on the Clock interface and use SystemClock for real time (with timezone support) or FrozenClock for deterministic, test-friendly time in unit tests.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • PSR-20 Compliance: The package fully implements the PSR-20 Clock Interface, ensuring alignment with modern PHP standards. This makes it a first-class citizen in Laravel ecosystems where time abstraction is critical (e.g., caching, rate limiting, scheduled jobs).
  • Dependency Injection Ready: The Clock interface is explicitly designed for DI, fitting Laravel’s service container and dependency injection patterns. This enables mocking time in tests without side effects.
  • Timezone Awareness: Explicit timezone handling (SystemClock::fromUTC(), SystemClock::fromSystemTimezone()) aligns with Laravel’s global timezone configuration (config/app.php), reducing ambiguity in distributed systems.
  • Immutable Design: SystemClock is marked as @immutable and readonly, preventing accidental state modification—a critical feature for thread-safe and predictable Laravel applications (e.g., queue workers, background jobs).

Integration Feasibility

  • Laravel Service Provider Integration:
    • Bind the Clock interface to a default implementation (e.g., SystemClock) in Laravel’s service container.
    • Allow runtime overrides (e.g., for testing) via config or environment variables.
  • Facade Compatibility:
    • Create a Laravel facade (e.g., Clock::now()) to abstract the interface, mirroring Laravel’s Cache, Auth, and Log facades.
  • Event Dispatching:
    • Integrate with Laravel’s event system to trigger time-based events (e.g., TimeAdjusted, ClockFrozen) when switching between SystemClock and FrozenClock.

Technical Risk

Risk Area Mitigation Strategy
PHP Version Mismatch Laravel 10+ requires PHP 8.2+. The package supports PHP 8.4+ (latest stable). Upgrade path: Test with Laravel’s PHP version matrix.
Breaking Changes PSR-20 adoption (v3.0.0) is backward-compatible with Laravel’s existing Carbon/DateTime usage. Risk: Minimal if using the interface.
Performance Overhead SystemClock uses DateTimeImmutable::now(), which is optimized in PHP. Benchmark against now() in Laravel’s Carbon facade.
Testing Complexity FrozenClock simplifies time manipulation in tests. Risk: Developers may forget to reset clocks post-test. Solution: Use Laravel’s test helpers or a ClockManager facade.

Key Questions

  1. How will time adjustments (e.g., daylight saving) be handled in SystemClock?
    • Answer: Delegates to PHP’s DateTimeImmutable, which accounts for timezone rules. No additional logic needed.
  2. Can FrozenClock be used in production?
    • Answer: No. It’s purely for testing. Use SystemClock in production.
  3. How does this interact with Laravel’s Carbon facade?
    • Answer: The package returns DateTimeImmutable objects, which Carbon can instantiate from. No direct conflict.
  4. What’s the migration path from now() to Clock::now()?
    • Answer: Use Laravel’s alias feature to map now() to Clock::now() temporarily during transition.
  5. Does this support custom time sources (e.g., NTP, database-backed clocks)?
    • Answer: Extend the Clock interface to implement a custom provider (e.g., DatabaseClock).

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Container: Bind Clock interface to SystemClock in AppServiceProvider.
    • Facades: Create Clock facade for fluent access (e.g., Clock::now()).
    • Testing: Use FrozenClock in PHPUnit tests via createMock(Clock::class) or Laravel’s partialMock.
  • Compatibility:
    • Carbon: Works seamlessly since DateTimeImmutable is interchangeable with Carbon\Carbon.
    • Queues/Jobs: Replace now() with Clock::now() in job classes for deterministic testing.
    • Events: Integrate with Laravel’s scheduler and events systems for time-based triggers.

Migration Path

Phase Action Tools/Techniques
Assessment Audit all now()/Carbon::now() usages in codebase. grep, IDE refactoring tools.
Interface Adoption Replace direct DateTimeImmutable instantiation with Clock interface. Laravel IDE Helper, Rector.
Facade Rollout Introduce Clock facade and alias now() to Clock::now(). Laravel’s aliases.php.
Testing Replace DateTime::createFromFormat() in tests with FrozenClock. Laravel’s refreshDatabase() + FrozenClock.
Production Deploy with SystemClock as default; monitor for timezone edge cases. Sentry, Laravel Logs.

Compatibility

  • Laravel Versions:
    • Laravel 10+: Full compatibility (PHP 8.2+).
    • Laravel 9.x: Requires PHP 8.1+ (use v3.2.0 of the package).
    • Laravel 8.x: Not recommended (PHP 8.0 support dropped in v3.1.0).
  • Third-Party Packages:
    • PSR-20 Adopters: Seamless integration (e.g., spatie/laravel-activitylog).
    • Non-PSR-20: Wrap legacy packages in a Clock-aware adapter.

Sequencing

  1. Core Services:
    • Start with authentication, rate limiting, and scheduling (highest now() usage).
  2. Background Jobs:
    • Replace now() in job classes to enable replayable tests.
  3. API Layer:
    • Update DTOs/responses using time (e.g., created_at) to use Clock.
  4. UI/Blade:
    • Replace now()->format() with Clock::now()->format() in templates.

Operational Impact

Maintenance

  • Dependency Updates:
    • The package is actively maintained (last release: 2026-04-13). Use Composer’s update or Laravel Forge for updates.
  • Backward Compatibility:
    • PSR-20 adoption (v3.0.0+) is stable. Minor versions are safe for Laravel.
  • Debugging:
    • Log Clock usage in Laravel’s app.php to trace time-related issues:
      Clock::shouldLogUsage(true); // Hypothetical feature; use middleware otherwise.
      

Support

  • Documentation:
    • Internal Docs: Add a TIME_ABSTRACTION.md in Laravel’s docs repo with:
      • Clock interface usage.
      • FrozenClock testing patterns.
      • Common pitfalls (e.g., forgetting to reset clocks).
    • External: Link to PSR-20 and the package’s README.
  • Troubleshooting:
    • Timezone Issues: Use SystemClock::fromUTC() in CI/CD to avoid DST surprises.
    • Test Failures: Add a ClockReset trait to Laravel’s test case base class.

Scaling

  • Performance:
    • SystemClock is stateless and thread-safe. No scaling concerns in Laravel’s request/queue model.
    • Benchmark: Compare Clock::now() vs. now() in a load-tested Laravel app (e.g., 10K RPS).
  • Distributed Systems:
    • Use SystemClock with UTC to avoid timezone inconsistencies across microservices.
    • For eventual consistency, consider a custom Clock implementation that syncs with a distributed time source (e.g., Chronos).

Failure Modes

Failure Scenario Impact Mitigation
Clock Not Bound in Container Clock resolution fails. Use Laravel’s bindIf() in AppServiceProvider.
FrozenClock in Production Time stands still. Runtime check: Throw RuntimeException if FrozenClock is detected.
Timezone Mismatch Inconsistent timestamps. Enforce UTC in SystemClock for APIs.
**Clock
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony