Skip to content

Instantly share code, notes, and snippets.

@Nex-Otaku
Last active April 15, 2020 21:34
Show Gist options
  • Save Nex-Otaku/622ce7f2f336f27b4953e85efffa7c45 to your computer and use it in GitHub Desktop.
Save Nex-Otaku/622ce7f2f336f27b4953e85efffa7c45 to your computer and use it in GitHub Desktop.
<?php
class Timestamp
{
/** @var int */
private $intTimestamp;
private function __construct(int $intTimestamp)
{
$this->intTimestamp = $intTimestamp;
}
public static function createNew(): self
{
return new self(time());
}
public static function createFromInt(int $intTimestamp): self
{
return new self($intTimestamp);
}
public function toInt(): int
{
return $this->intTimestamp;
}
public function toString(): string
{
try {
$result = (new \DateTime("@{$this->intTimestamp}"))
->setTimezone(new \DateTimeZone('Europe/Moscow'))
->format('Y-m-d H:i:s');
} catch (\Exception $exception) {
throw new \LogicException("Не удалось сконвертировать время, Timestamp: {$this->intTimestamp}");
}
return $result;
}
}
@Nex-Otaku
Copy link
Author

Nex-Otaku commented Apr 8, 2020

Комментарий от Дмитрия Дерепко (@xepozz):

либо
Interface::class=>[
'__construct()' => [
$formatter
]
]
либо
Interface::class=>[
'setFormatter()' => [
$formatter
]
]
$formatter может быть либо объектом, либо ссылкой (DI\Reference)

@Nex-Otaku
Copy link
Author

Nex-Otaku commented Apr 8, 2020

@Nex-Otaku
Copy link
Author

Есть простой объект, для хранения timestamp. В него инкапсулируется всё, что касается Timestamp.

В коде, я могу создавать текущий Timestamp, или на конкретную секунду из целого числа, а также конвертировать в целое число или пеерводить в форматированную строку для представления на экране.

И тут у меня возникает необходимость сделать несколько форматов. Причём форматы будут определяться динамически в зависимости от настроек окружения.

Я выношу форматирование в отдельный объект, обращаюсь через TimestampFormatterInterface, всё хорошо.

Но встаёт проблема. Как мне получить конкретный TimestampFormatter в каждом объекте Timestamp?

Прокинуть в зависимость в конструкторе?

Но тогда придётся менять весь код, который уже использует Timestamp. В каждый Timestamp::createNew() и каждый Timestamp::createFomInt() придётся дописывать дополнительный параметр.

Это явно плохая идея, так как реально меняется только сам Timestamp, от этого не должны страдать прочие классы.

Вопрос - как сделать?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment