Watch your Clock

After more than a year talking about it, there finally is a common interface for clock-implementations available.

And no: It’s not (yet) PSR-20.

After a personally frustrating time within the PSR-20 working group I just recently (rage-) quit my work there. And the most frustrating part for me was that we were discussing something that is already there. There are Clock-Implementations around. And each of them is using an interface (otherwise it doesn’t work). And each of them is defining their own interface with exactly the same signature. The one that is currently discussed in the Working Group over and over again.

So after I quit I took a step back and thought about what was more important: A PSR-implementation or a Common interface that allows interoperability. And in the end, all we want is the interoperability part.

So I recreated the interface that the Working Group was discussing and that is already implemented in clock-implementations in the wild, created a package from that and created some pull-requests.

And since yesterday 3 of the most widely used (more than 25 million installs combined) clock-implementations use the same publicly available clock-interface:

stella-maris/clock

To see implementations using this common interface check out packagist.org

Temporary Solution

I only see that as a temporary solution though. My main goal would still be to have a PSR-20 implementation out and usable. Therefore the idea is – once the current draft is published – to extend that interface. So that all implementations that are currently implementing the stella-maris/clock interface will then – without any work from their side – immediately also implement PSR-20. At least when the currently discussed interface will be published. Should the interface differ from that, every implementation will need to create a separate implementation anyhow due to their currently different design.

So while this might not be a 100% solution, it is already an 80% solution. And an 80% solution that is usable right now.

Usage

So how can you use this interoperable clock-interface.

Install it via composer: `composer require stella-maris/clock`

And then adapt your PHP-Code like this:

use StellaMaris\Clock\ClockInterface;

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

    public function do()
    {
        // Provides you with a DateTimeImmutable referencing 
        // the current point in time
        $clock->now();
    }
}

So when you are using a clock implementation like lcobucci/clock or kreait/clock the only thing you need to do to be interoperable is to replace the reference to Lcobucci\Clock\Clock or Kreait\Clock with StellaMaris\Clock\ClockInterface and you are done.