I'm trying to call the method of a loaded model by a variable name instead of a hard coded method name. This will give me a ton of abstraction in my controller without using a bunch of if-then statements.
Here's the Model
class Reports_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function backlog()
{
//Do stuff
}
What I want is to be able to call the backlog function by a variable name. Here's the controller:
class Reports extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function get_reports($report_name)
{
$this->load->model('reports_model');
$report_name = 'backlog';
$data['data'] = $this->reports_model->$report_name();
}
From what I can tell (and I'm probably missing something stupid), my code is exactly like Example #2 on http://php.net/manual/en/functions.variable-functions.php, but I'm getting this error at the line of the function call:
Undefined property: Reports::$reports_model
You can use autoloader for this model. Autoloader file is in appilication/config/ folder. You must you model in
$autoload['model'] = array('Reports_model');
Or you can use
class Reports extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Reports_model');
}
public function get_reports($report_name)
{
$report_name = 'backlog';
$data['data'] = $this->Reports_model->backlog();
}
}
You must be write upper first character of the model like this : $this->Reports_model->backlog()
http://codeigniter.com/user_guide/general/models.html#anatomy
You did not load the reports model, change your constructor in the controller:
public function __construct() {
parent::__construct();
$this->load>model('Reports_model');
}