CodeIgniter Forums
Time::now() in every controller - Printable Version

+- CodeIgniter Forums (
+-- Forum: CodeIgniter 4 (
+--- Forum: CodeIgniter 4 Support (
+--- Thread: Time::now() in every controller (/showthread.php?tid=75906)

Time::now() in every controller - beng - 03-28-2020

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,

RE: Time::now() in every controller - Codinglander - 03-29-2020

I'm also interested in that. I read with ..

RE: Time::now() in every controller - maxxd - 03-29-2020

Put it in BaseController, then assign an instance to a class property in the constructor, like so:

PHP Code:
namespace App\Controllers;

 * Class BaseController
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 * For security be sure to declare any new methods as protected or private.
 * @package CodeIgniter

use CodeIgniter\Controller;

BaseController extends Controller

     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     * @var array
protected $helpers = [];

     * Constructor.
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
// Do Not Edit This Line

        // Preload any models, libraries, etc, here.
        // E.g.:
        // $this->session = \Config\Services::session();
$this->time = new Time();

Then you can call it from any controller extending BaseController like so:

PHP Code:

RE: Time::now() in every controller - beng - 03-29-2020

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.