PHP code example of php-architecture-kit / clock

1. Go to this page and download the library: Download php-architecture-kit/clock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

php-architecture-kit / clock example snippets


use PhpArchitecture\Clock\SystemClock;
use PhpArchitecture\Clock\FrozenClock;
use PhpArchitecture\Clock\LocalizedClock;

// Production: Use system clock
$clock = new SystemClock();
$now = $clock->now(); // DateTimeImmutable

// Testing: Use frozen clock
$clock = FrozenClock::at(new \DateTimeImmutable('2024-06-15 12:00:00'));
$now = $clock->now(); // Always returns '2024-06-15 12:00:00'

// Timezone-specific: Use localized clock
$clock = new LocalizedClock(new \DateTimeZone('Europe/Warsaw'));
$now = $clock->now(); // DateTimeImmutable in Warsaw timezone

// UTC shortcut
$clock = LocalizedClock::utc();

$clock = new SystemClock();
$now = $clock->now(); // Current time

// Freeze at specific time
$clock = FrozenClock::at(new \DateTimeImmutable('2024-01-01 00:00:00'));

// Freeze at current time
$clock = FrozenClock::fromNow();

// Time never changes
$clock->now(); // Always the same
usleep(10000);
$clock->now(); // Still the same

// Any timezone
$clock = new LocalizedClock(new \DateTimeZone('America/New_York'));

// UTC shortcut
$clock = LocalizedClock::utc();

$now = $clock->now();
echo $now->getTimezone()->getName(); // 'America/New_York' or 'UTC'

use Psr\Clock\ClockInterface;

class OrderService
{
    public function __construct(
        private ClockInterface $clock
    ) {}

    public function createOrder(array $items): Order
    {
        return new Order(
            items: $items,
            createdAt: $this->clock->now()
        );
    }
}

// Symfony
services:
    Psr\Clock\ClockInterface:
        class: PhpArchitecture\Clock\SystemClock

// Laravel
$this->app->bind(ClockInterface::class, SystemClock::class);

class OrderServiceTest extends TestCase
{
    public function testOrderCreatedWithCorrectTimestamp(): void
    {
        $fixedTime = new \DateTimeImmutable('2024-06-15 12:00:00');
        $clock = FrozenClock::at($fixedTime);
        
        $service = new OrderService($clock);
        $order = $service->createOrder(['item1', 'item2']);
        
        $this->assertEquals($fixedTime, $order->getCreatedAt());
    }
}
bash
composer