Time::now() in every controller |
Hi there,
I know there will be a really simple answer to this that I am missing. I want to use CI4's datetime class in pretty much every controller e.g.: PHP Code: echo Time::now() PHP Code: $myTime = new Time('+3 week'); But I dont want to have to put: PHP Code: use CodeIgniter\I18n\Time; At the top of every controller. Is there a way I can autoload the class? I have already tried adding to the Autoload config in the $psr4 section and I have also tried adding the line to the top of the BaseController but nothing seems to work? Am I missing something - could someone shed some light on this please. Many thanks, Ben
Put it in BaseController, then assign an instance to a class property in the constructor, like so:
PHP Code: <?php Then you can call it from any controller extending BaseController like so: PHP Code: $this->time->now();
Hi Maxxd,
Was thinking that but worried any time I use $this->time in controllers it would be using the same instance of the class - not good for date comparisons etc. Thinking about it I suppose I could just do: $var1 = $this->time; $var2 = $this->time; This would then create 2 versions of the class I'm guessing... Would I be correct in also saying that as new Time(); would have been called without defaults I would then have to use $var2::parse() to set times etc? Thanks for you advice on this. |
Welcome Guest, Not a member yet? Register Sign In |