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 Bundle Laravel Package

comsolit/clock-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require comsolit/clock-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Comsolit\ClockBundle\ComsolitClockBundle::class => ['all' => true],
    ];
    
  2. First Use: Inject the Clock service into your controller/service:

    use Comsolit\ClockBundle\Clock\ClockInterface;
    
    public function __construct(private ClockInterface $clock) {}
    
  3. Basic Usage:

    $currentTime = $clock->getDateTime(); // Request-constant DateTime
    $timestamp = $clock->getTimestamp(); // Unix timestamp
    

Implementation Patterns

Time-Consistent Request Handling

  • Use Case: Ensure all time checks in a request use the same reference point.

    // In a login controller
    if ($clock->hasElapsed(300, $lastAttempt->getDateTime())) {
        $this->allowLogin();
    }
    
  • Workflow:

    1. Inject ClockInterface into services/controllers.
    2. Replace direct new DateTime() calls with $clock->getDateTime().
    3. Use helper methods (hasElapsed, isExpired) for readability.

Testing Time-Dependent Logic

  • Pattern: Mock the Clock service in tests to simulate time progression.

    // tests/Feature/LoginTest.php
    public function testLoginBlockAfterFailures()
    {
        $this->mock(ClockInterface::class, function ($mock) {
            $mock->shouldReceive('hasElapsed')
                 ->with(300, $lastAttempt->getDateTime())
                 ->andReturn(true);
        });
    }
    
  • Integration Tip:

    • For complex time logic, create a ClockAwareTrait to centralize clock usage:
      trait ClockAware {
          public function __construct(private ClockInterface $clock) {}
      
          protected function isBlocked(DateTimeInterface $lastAttempt, int $blockingPeriod): bool {
              return $this->clock->hasElapsed($blockingPeriod, $lastAttempt);
          }
      }
      

File Naming and Logging

  • Use Case: Generate time-based filenames or log timestamps consistently.
    $fileName = $clock->getFileName() . '_backup.csv'; // e.g., "2023-11-15_14-30-00_backup.csv"
    $this->logger->info('Backup started', ['timestamp' => $clock->getTimestamp()]);
    

Gotchas and Tips

Pitfalls

  1. Request-Scoped Time:

    • The clock’s time does not advance during a single request. If you need to simulate time progression in tests, mock the entire ClockInterface.
    • ❌ Avoid:
      // Fails: Clock time doesn't change mid-request
      $clock->getTimestamp() + 1000; // Always uses the same timestamp
      
  2. DateTime Mutability:

    • Never modify the DateTime instance returned by $clock->getDateTime(). It’s managed by the bundle.
    • ❌ Avoid:
      $now = $clock->getDateTime();
      $now->modify('+1 hour'); // May break internal state
      
  3. Time Zone Assumptions:

    • The clock uses the system’s default time zone. Explicitly set it if needed:
      $clock->setTimeZone(new \DateTimeZone('Europe/Berlin'));
      

Debugging

  • Verify Clock Time: Add a debug dump to confirm the clock’s time isn’t advancing unexpectedly:

    \Log::debug('Clock timestamp:', ['ts' => $clock->getTimestamp()]);
    
  • Test Mocking: Ensure test mocks return consistent values:

    $mock->shouldReceive('getTimestamp')
         ->andReturn(1634567890); // Fixed timestamp for tests
    

Extension Points

  1. Custom Clock Implementations: Override the default clock for specialized needs (e.g., frozen time for tests):

    # config/services.yaml
    services:
        App\Clock\CustomClock:
            arguments:
                $timeZone: 'UTC'
            tags: ['clock']
    
  2. Helper Methods: Extend the clock with domain-specific helpers:

    // src/Clock/ExtendedClock.php
    class ExtendedClock implements ClockInterface {
        public function isWeekend(): bool {
            return $this->getDateTime()->format('N') > 5;
        }
    }
    
  3. Configuration: The bundle has minimal config. Override defaults via config/packages/comsolit_clock.yaml:

    comsolit_clock:
        default_timezone: 'America/New_York'
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours