Welcome Guest, Not a member yet? Register   Sign In
Time::now() in every controller
#1

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() 
or
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
Reply
#2

I'm also interested in that. I read with ..
Reply
#3

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

PHP Code:
<?php
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;
use 
CodeIgniter\I18n\Time;

class 
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
        
parent::initController($request$response$logger);

        
//--------------------------------------------------------------------
        // 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:
$this->time->now(); 
Reply
#4

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB