Welcome Guest, Not a member yet? Register   Sign In
Auto load cache driver with parameters
#1

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?
Reply
#2

(This post was last modified: 06-20-2015, 09:34 AM by CroNiX.)

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()
  {
    //...
  }
}
Reply
#3

CroNiX,

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




Theme © iAndrew 2016 - Forum software by © MyBB