Welcome Guest, Not a member yet? Register   Sign In
how to pass argument to model constructor while loading a model
#1

[eluser]pankaj[/eluser]
how to pass argument to model constructor while loading a model normally we follow
Code:
$this->load-model('user');
but I want to send parameters to this models constructor. Please explain me how to do this.
#2

[eluser]Evil Wizard[/eluser]
A library can accept __constructor parameters but the model doesn't see to. The alternative is to create an initialise() method that will accept your construct params.
Code:
class user_model extends model {
    public function __construct()
    {
        parent::__construct();
    }
    public function initialise($param1, $param2=NULL)
    {
        $this->param1 = $param1;
    }
}
then
Code:
$this->load->model('user_model');
$this->user_model->initialise('param1', 'param2');
#3

[eluser]TheFuzzy0ne[/eluser]
I second that. It's always a good idea to have an initialisation method which you can call from the constructor if need be, although in your case, it's pretty pointless if you're loading the model via CodeIgniter's loader.

I'd like to point out, however, that it's probably wiser to stick to the US spelling, so your method should be called initialize().
#4

[eluser]lezeroq[/eluser]
Maybe someone is still interested in this issue. You can modify system library system/libraries/Loader.php, replace
Code:
function model($model, $name = '', $db_conn = FALSE)
{
  //...
  //...
    $CI->$name = new $model();
    $CI->$name->_assign_libraries();
    $this->_ci_models[] = $name;    
}
with
Code:
function model($model, $name = '', $db_conn = FALSE)
{
  //...
  //...

    if (func_num_args() > 3) {
        $refl = new ReflectionClass($model);
        $CI->$name = $refl->newInstanceArgs(array_slice(func_get_args(), 3));
    } else {
        $CI->$name = new $model();
    }
    $CI->$name->_assign_libraries();
    $this->_ci_models[] = $name;    
}
Example model with arguments in construcrot:
Code:
class ExampleModel extends Model {

    function __construct($param1, $param2)
    {
        parent::Model();

        // do some with params
    }

    //...
}
Now you can pass yours parameters from controller to a models constructor after the first three arguments
Code:
$this->load->model('ExampleModel', '', FALSE, $param1, $param2);
Sorry for my enslish Smile
#5

[eluser]Unknown[/eluser]
I think this is an excellent extension - maybe improved only by making the 4th param an optional array, and then handling namespace variables like passage in views.

Is this approach headed for core?
#6

[eluser]MathBoon[/eluser]
This would really be a nice extension, i vote for making this another core element Wink
#7

[eluser]Andreas Bergström[/eluser]
This helped me a lot, I second putting this in the core.
#8

[eluser]Unknown[/eluser]
Love it, has it been added yet?




Theme © iAndrew 2016 - Forum software by © MyBB