Answer the question
In order to leave comments, you need to log in
Setting timezone within module?
Is it possible in php to set the default timezone only within the same file or class?
The fact is that I have some module that calculates taking into account the user's time. date_default_timezone_set()
I can’t use it, as it will lead to incorrect work of the rest of the code. And in the module, when creating an DateTime
object (which occurs in a dozen different places), it is not very convenient to set a zone for it every time. In addition, given that the module uses several third-party classes in its work, you will have to redo them and implement zone transfer from the class using them. Obviously, this is not the best solution.
Please tell me what is the best thing to do in this situation.
Answer the question
In order to leave comments, you need to log in
All this is done at the application level. This is an architectural problem ..
1. You must have a config in each module or a place from where you will take the time zone
.
src/modules/user
- timezone.ini
src/modules/customers
- timezone.ini
src/modules/admin
- timezone.ini
src/modules/user/
- DIC.php
- ...
- UserController.php
- timezone.ini
src/
- TimeZone.php
# timezone.ini
timezone=Europe/Kiev
# TimeZone.php
class TimeZone() {
private $tz;
public __constructor($tz) {
$this->tz = $tz;
}
public function getDateTime() {
$currentDate = (new \DateTime())->format('Y-m-d H:i:s');
$tz = new DateTimeZone($config['timezone']);
$date = new DateTime($currentDate);
$date->setTimezone($this->tz);
return $date;
}
}
# DIC.php
use src/TimeZone;
use UserController;
class DIC {
private function getTimeZone() {
$config = parse_ini_file('timezone.ini');
retrun new TimeZone($config['timezone']);
}
public function getUserModule() {
return new UserController(
($this->getTimeZone()->getDateTime())
)
}
}
# UserController.php
class UserController {
protected $date;
public function __constructor(\DateTime $date) {
$this->date = $date // Можно расшарить между внутренними компонентами модуля
}
}
# У каждого компонента параметр со своей временной меткой
$dic = new DIC();
$userModule = $dic->getUserModule();
$customerModule = $dic->getCustomerModule();
$adminModule = $dic->getAdminModule();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question