balinoff / 时钟
简单的时钟抽象
1.0.1
2021-01-04 15:33 UTC
Requires
- php: >=7.4
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- phpunit/phpunit: ^9.3
- vimeo/psalm: ^4.0
This package is auto-updated.
Last update: 2024-09-23 13:52:30 UTC
README
以静态和可测试的方式获取当前时间。
安装
您可以通过composer安装此包
composer require baldinof/clock
静态使用
use Baldinof\Clock\Clock; $now = Clock::now(); assert($now instanceof \DateTimeImmutable);
为什么使用静态调用而不是依赖注入?
静态调用在定义模型时非常方便
use Baldinof\Clock\Clock; use Ramsey\Uuid\Uuid; final class User { private $id; private $createdAt; private $name; public function __construct(string $name) { $this->id = Uuid::uuid4(); $this->createdAt = Clock::now(); $this->name = $name; } // Getters... }
测试
您可以在测试开始时使用FrozenClockTrait
冻结时钟并操纵时间。
use Baldinof\Clock\Testing\FrozenClockTrait; use Baldinof\Clock\Clock; use PHPUnit\Framework\TestCase; final class UserTest extends TestCase { use FrozenClockTrait; public function test_it_is_initialized_with_current_time() { $user = new User("John"); $this->assertEquals(Clock::now(), $user->createdAt()); } }
您还可以显式地操纵时钟
use Baldinof\Clock\Testing\FrozenClockTrait; use Baldinof\Clock\Clock; use PHPUnit\Framework\TestCase; final class UserTest extends TestCase { use FrozenClockTrait; public function my_function() { // Set the clock at a specified time. $this->freezeClock(new \DateTimeImmutable('2000-01-01')); // Add an hour to the clock. $this->modifyClock('+1 h'); // Reset the clock. $this->restoreSystemClock(); } }
时区
默认情况下,Clock::now()
不会将时区参数传递给DateTimeImmutable
构造函数,因此使用的是php默认时区。
您可以在php.ini
中更改默认时区。
否则,在您的应用程序引导代码中调用date_default_timezone_set()
或调用Clock::set()
<?php use Baldinof\Clock\Clock; use Baldinof\Clock\SystemClock; // Change the clock implementation Clock::set(SystemClock::forTimeZone('UTC')); // or change the default timezone date_default_timezone_set('UTC');
与依赖注入一起使用
您可以通过调用Clock::get()
获取实际的时钟实例并将其注册到依赖注入容器中。
例如使用Symfony PHP DSL
use Baldinof\Clock\Clock; use Baldinof\Clock\ClockInterface; return function (ContainerConfigurator $container) { $services = $container->services(); $services ->set(ClockInterface::class) ->factory([Clock::class, 'get']); };
或者使用Laravel
// In a service provider $this->app->instance(ClockInterface::class, Clock::get());
变更日志
请参阅变更日志获取最近更改的更多信息。
致谢
此包受lcobucci/clock和ramsey/uuid的静态使用启发。
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。