Search code examples
phpfunctioncodeignitermethodscontrollers

Codeigniter - Appending variables names to a method name to run Model function


Not sure if possible but what I am trying to do is pass a query string through a get request to my controller. From here I am getting the query string value using $_GET['name']. What I would like to do then is use that GET value and append it as the name of the method I will be passing to my Model to return the data I need.

This is because multiple action with pass different query string values to the same controller but then use the value to get the data from different functions within my model.

e.g.

Controller

class ControllerName extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('my_model');
    }

    public function index() {
        $queryName = $_GET['query_string']
        // e.g. $queryName = 'customer'

        //Use the query string and append to method to pass to Model function
        $result = $this->my_model->$queryName._get_query(); //???

       //e.g. $result = $this->my_model->customer_get_query();
    }
}

My_model

class My_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->load->database();
    }

    function customer_get_query() {
        //...run database query and return result
    }
}

Any thoughts?


Solution

  • The usual php should work just fine:

    $result = call_user_func([$this->my_model, $queryName.'_get_query']);