nanaweb/clock

面向对象编程的时钟对象

v1.0.2 2020-05-26 13:18 UTC

This package is auto-updated.

Last update: 2024-08-26 22:46:48 UTC


README

安装

$ composer require nanaweb/clock

使用

now()

将此方法注入需要当前时间戳的类中,并调用 $this->clock->now() 获取当前时间戳。

<?php

class SomeClass
{
    private $clock;

    public function __construct(\Nanaweb\Clock $clock)
    {
        $this->clock = $clock;
    }

    public function getFiveHourLater()
    {
        /** @var \DateTimeImmutable $now */
        $now = $this->clock->now();

        return $now->add(new \DateInterval('PT5H')); //
    }
}

today()

将此方法注入需要当前日期的类中,并调用 $this->clock->today() 获取当前日期。

<?php

class SomeClass2
{
    private $clock;

    public function __construct(\Nanaweb\Clock $clock)
    {
        $this->clock = $clock;
    }

    public function getFiveDaysAgo()
    {
        /** @var \DateTimeImmutable $today */
        $today = $this->clock->today();

        return $today->sub(new \DateInterval('P5D')); // 00:00:00 of five days ago
    }
}

为什么我要使用Clock?

为了测试对时间敏感的类。

<?php

class SomeClassTest extends TestCase
{
    public function test_fiveHoursAgo()
    {
        $clockP = $this->prophesize(\Nanaweb\Clock::class);
        $clockP->now()->willReturn(new \DateTimeImmutable('2020-05-16 10:00:00'))->shouldBeCalled();

        $SUT = new SomeClass($clockP->reveal());
        $this->assertEquals('2020-05-16 15:00:00', $SUT->getFiveHoursLater());
    }
}