CodeIgniter Forums
Auto load cache driver with parameters - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=11)
+--- Thread: Auto load cache driver with parameters (/showthread.php?tid=62217)



Auto load cache driver with parameters - amit - 06-20-2015

I know I can load a particular caching driver in a controller with options as second parameters:
Code:
$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));

I wonder if is there any way to auto load the same using autoload.php under application/config as I can specify
Code:
$autoload['drivers'] = array('cache');

but unable to pass parameters here. So my question is how can I autoload caching driver with specifying some parameters along with?


RE: Auto load cache driver with parameters - CroNiX - 06-20-2015

You can create a library that does it in it's construct(), and autoload the library. You can create a MY_Controller, and do it in the construct() and then have all of your other controllers extend MY_Controller instead of CI_Controller. There may be other ways but those are 2 that I know will work. Both will load and execute before your regular controllers get called.

Library method:
/application/libraries/Cacher.php
Code:
class Cacher {
  protected $CI;

  public function __construct()
  {
    $this->CI =& get_instance(); //grab an instance of CI
    $this->initiate_cache();
  }

  public function initiate_cache()
  {
    $this->CI->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
  }
}
Then add it to your autoloader
Code:
$autoload['libraries'] = array('cacher');


MY_Controller method:
/application/core/MY_Controller.php
Code:
class MY_Controller extends CI_Controller {
  public function __construct()
  {
    parent::__construct();
    $this->initiate_cache();
  }

  private function initiate_cache()
  {
    $this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
  }
}

Then, your controllers -> extends MY_Controller: /application/controllers/Something.php
Code:
class Something extends MY_Controller {
  public function __construct()
  {
    parent::__construct();
  }

  public function index()
  {
    //...
  }
}



RE: Auto load cache driver with parameters - amit - 09-02-2015

CroNiX,

Thank you much. It's what I was looking for.