How can I get the a model instance dinamicaly?


(Santiago Carmo) #1

Hi folks,

I’m creating a generic controller to be used in a model, this controller will work with any modules, but in some actions I’ll need to pass a model instance, like this:




public actionCreate()

{

  $model = new MYACTUALMODEL;

  //do some thing ...

}



Some controllers on my app will extend this controller.

A inportant note:

Normally the controller name and de model name will be the same, so:




//if the controller name is:

PersonController

//the model name will be:

Person



So I need know:

How can I get a model instance dinamicaly to use in place of MYACTUALMODEL ?

Thanks.


(Arekandrei) #2

Seems you want something like this (in the parent controller):




public actionCreate()

{

    $model = new $this->id;

    //do some thing ...

}




(O Rijkers) #3

you can also use the get_called_class() function within the controller class. If you then strip of the last part of the class name (i.e. ‘Controller’), you then have your model name.


(Santiago Carmo) #4

Hi guys, first of all, thanks for answer my post.

Onman, I saw your tip, but the get_called_class() return the class name as a string and I can’t use a string to instantiate a object.

For exemple $c = new ‘MODELNAME’ don’t work, becouse ‘MODELNAME’ is a string, the idea is good, but have this problem.

Andy_s I don’t understand what you said, if I use “$this” on action controller I think that I will references the parent controller class and not the model class.

I need to create a model instance based on controller name.

Thanks.


(Santiago Carmo) #5

Onman,

after do alot of test I found that I can’t instantiate a class using a string, but if I put this string in a variable, I can use it to instantiate a class, like this:




$v = "classname";

$t = new $v;



Now I’ll try this on my project and after I’ll put the result here.

Thanks


(Arekandrei) #6

$this->id references to the current controller’s id. If you have controller PersonController extending GenericController, it will return “Person”. So if you want to create some common methods in your generic controller where you instantiate some models (and you assume that a model of PersonController has name Person), you can do it this way (in GenericController’s method): $model = new $this->id. So when you extend GenericController with PersonController, $this->id will return “Person”.

Sorry if I understood you wrong.


(Mh) #7

To make it more clean you could put the logic for model creation into it’s own method in the parent controller:


private $_model;

public function getModel()

{

    // Find out model name here, e.g. like andy_s suggested

    $modelname=$this->id;

    if($this->_model===null)

      $this->_model = new $modelname;

    return $this->_model

}



In any extended controller (and even view) you can access that model easily with $this->model;