elstc / cakephp-time-interval
用于 CakePHP 的时间间隔类型插件
v3.0.0
2024-05-01 06:45 UTC
Requires
- php: >=8.1
- ext-json: *
- ext-pdo: *
- cakephp/cakephp: ^5.0
Requires (Dev)
- cakephp/cakephp-codesniffer: ^5.0
- cakephp/migrations: ^4.0
- phpunit/phpunit: ^10.1
README
此插件为 MySQL 的 TIME
、Postgres 的 INTERVAL
提供了 time_interval
自定义类型,并为秒提供了 time_interval_int
自定义类型。这是一个表示间隔的自定义类型,CakePHP 可以将其视为从 DateInterval
继承的 TimeInterval
对象。
版本映射
安装
您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。
安装 composer 包的推荐方式是
composer require elstc/cakephp-time-interval
加载插件
通过在项目的 src/Application.php
中添加以下语句来加载插件
$this->addPlugin('Elastic/TimeInterval');
用法
向 Table 类添加列定义
use Cake\Database\Schema\TableSchema; class WorkTimesTable extends Table { protected function _initializeSchema(TableSchema $schema) { parent::_initializeSchema($schema); $schema->setColumnType('duration', 'time_interval'); // If your column type is seconds as INTEGER, Use `time_interval_int` instead. $schema->setColumnType('duration_sec', 'time_interval_int'); return $schema; } }
向 Table 类添加列验证
使用 timeInterval
规则而不是 time
。 timeInterval
规则位于 timeInterval
验证提供者中。
use Cake\Validation\Validator; use Elastic\TimeInterval\Validation\TimeIntervalValidation; class WorkTimesTable extends Table { public function validationDefault(Validator $validator) { // ... $validator->add('duration', 'timeInterval', [ 'rule' => 'timeInterval', 'provider' => 'timeInterval', ]); return $validator; } }
此外,向 Entity 类添加修改器,这很有用。
use Cake\Database\Type; class WorkTime extends Entity { protected function _setDuration($value) { // convert to TimeInterval return Type::build('time_interval')->marshal($value); } } $workTime->duration = '00:15:00'; $workTime->duration = ($startTime)->diff($endTime); // $startTime, $endTime is FrozenTime object. $workTime->duration = 3600; // as a seconds
注意
MySQL TIME 列限制。
MySQL :: MySQL 8.0 参考手册 :: 13.2.3 TIME 类型
By default, values that lie outside the TIME range but are otherwise valid are clipped to the closest endpoint of the range. For example,
'-850:00:00' and '850:00:00' are converted to '-838:59:59' and '838:59:59'. Invalid TIME values are converted to '00:00:00'.
Note that because '00:00:00' is itself a valid TIME value, there is no way to tell, from a value of '00:00:00' stored in a table,
whether the original value was specified as '00:00:00' or whether it was invalid.
与日期部分构造的 DateInterval / TimeInterval 将损坏时间
如果您使用日期部分初始化 DateInterval,时间将无法正确解释。
$workTime->duration = new DateInterval('PT75H4M5S'); // OK $workTime->duration = new DateInterval('P1M2DT3H4M5S'); // can't get expected time