Published at 09 December 2019

In PHP, you can easily the current time by simply creating a DateTime(Immutable) instance. In cases where time (or the passing of time) is important, introducing a system clock can be very beneficial. A system clock is used to provide the notion of time to you application. Because the interface is very simple, it’s also simple to fixate for testing purposes.

EventSauce is shipped with two implementations of the EventSauce\EventSourcing\Time\Clock interface. The EventSauce\EventSourcing\Time\SystemClock supplies the current time, and the EventSauce\EventSourcing\Time\TestClock can be fixated and manipulated for testing purposes.

Using the Clock


use EventSauce\EventSourcing\PointInTime;
use EventSauce\EventSourcing\Time\SystemClock;

// By default the UTC time zone is used, you can specify the one you need.
$clock = new SystemClock(/* optional */ new DateTimeZone('Europe/Amsterdam'));

/** @var DateTimeImmutable $dateTime */
$dateTime = $clock->dateTime();

/** @var PointInTime $pointInTime */
$pointInTime = $clock->pointInTime();

/** @var DateTimeZone $timeZone */
$timeZone = $clock->timeZone();

Using the TestClock

use EventSauce\EventSourcing\PointInTime;
use EventSauce\EventSourcing\Time\TestClock;

// By default the UTC time zone is used, you can specify the one you need.
$clock = new TestClock(/* optional */ new DateTimeZone('Europe/Amsterdam'));

// Ticking the clock sets the current time to "now".

// You can fixate the clock by specifying a point in time (format: Y-m-d H:i:s.u).
$clock->fixate('2020-02-02 02:02:02');

// moving the clock forward using a DateInterval
$clock->moveForward(new DateInterval('PT2H'));
Frank de Jonge

EventSauce is a project by Frank de Jonge.