Simple question: Can get I get model data, using a variable instead of a model name?

Hi,

I wanted to know how I could return a model, if the name of the model was in a variable…like this:




$model = $ModelName::model()->findAll();



Does anyone know if this is possible?

Thanks,

Matt

That will throw an error, what about:




$model=ModelName::model();

$model->findAll();



Yeah, just came up with that myself…I’m building a lookup table in an array, of models that I want to be part of the API I’m building.

I’m ok with that solution for now, unless anyone else has something better!

Thanks,

Matt

You could always store the Model names in the array and do smth like:




$models=array('Model1','Model2','Model3');

foreach($models AS $model){

  if(some condition){

    $m=new $model();

    $m->findAll();

  }

}



This has the advantage that you don’t keep an array of objects therefore should be less resource intensive if you’d have, say 1000 models to load (i doubt that anyway)

Unless ive misunderstood the question, I use this when the model class is dynamic…




$variable = 'Post';

$model = CActiveRecord::model($variable)->find();



I use it too, but as of PHP 5.3 the following syntax will also work:




$model = $variable::model()->findAll();



Awesome solutions guys…I guess I’m not on 5.3 yet…LOL.

For now I just have a lookup array of key/values, instantiated upon load…I’m sure this will be horrible later in production, so I’ll look at upgrading to php 5.3.

Cheers,

Matt

I have a similarly problem…

I defined in my class a variable $table_name, then a try to do :

$model = $this->table_name::model()->findByPk($id);

but it doesn’t work… I tried ($this->table_name)::model()->findByPk($id) but doesn’t work too…

do you have an idea ?

error : unexpected T_PAAMAYIM_NEKUDOTAYIM

Zugluk, you might try:

$model = {$this->table_name}::model()->findByPk($id);