Download the PHP package stratadox/clock without Composer
On this page you can find all versions of the php package stratadox/clock. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package clock
Clock
Factory for creating datetime objects.
What
It's really as simple as the name suggests: this is a clock, used to indicate what time it is.
Since it produces DateTime objects, this clock is somewhat special in the sense that it can also read the date.
![]()
Why
- As soon as you use "unadulterated" datetime objects in your code, any test
you've written for it immediately risks being flaky, because if there's a tiny
bit of time between
new DateTimeand your assertion, the test fails. - Instantiating a
new DateTimeornew DateTimeImmutablein client code, is a static invocation. This introduces coupling and reduces testability. This obviously goes double fordate_create()and the like. - It's a lot more natural to get the time from a clock than to instantiate a new instant each time you want to know how late it is.
Installing
Install with composer require stratadox/clock
Examples
Clock example
In a service that needs to know the time:
Rewindable clock example
In a service that needs to rewind or fast-forward the clock:
Choosing a clock
The default implementation is the DateTimeClock. It produces a new
DateTimeImmutable object whenever now is called.
If the datetime object needs to be passed into something that has a DateTime
type hint, or otherwise relies on mutable datetime objects, it is preferable to
solve that issue. For example by replacing the DateTime hint with
DateTimeIterface or DateTimeImmutable, or passing along a RewindableClock.
In cases where that is not an option, the DateTimeMutableClock clock can be
used instead.
In case timezones are important in your context, there is also a
TimeZoneAwareClock, which takes a timezone as constructor parameter.
To prevent the clock from ticking while other code is running, your tests can
instantiate and inject an UnmovingClock.
In a service definition:
In a unit test:
When the clock needs to be able to rewind or fast-forward, use the
RewindableDateTimeClock implementation.
In a service definition:
In a unit test:
Here's an overview of which clock to use when:
| Clock | When to use |
|---|---|
| DateTimeClock | In most situations |
| DateTimeMutableClock | When you can't use DateTimeImmutable |
| TimeZoneAwareClock | When the default timezone isn't enough |
| TimeZoneAwareMutableClock | When both two previous reasons apply |
| UnmovingClock | During testing |
| RewindableDateTimeClock | If the clock needs to be set back or forth |
Note that the rewindable clock can be combined with any other clocks, in order to produce, for instance, rewinded mutable datetime objects in a particular timezone.
