Confused In Instatiating A Model

I’m curious to know what the difference between some ways on how to instantiate a model. Let’s say I have a model named ‘User’, I found there are some ways to do it:




$model = new User;

//or

$model = User::model(); // this one is usually followed by chaining to other method, like User::model()->findAll(), but let's assume that there is no chained method.

//or

$model = CActiveRecord::model('User'); // I guess this one will have the same result as 2nd (or not)?



What situation is each syntax better used in?

As per my understanding…

1st one is used when you want to use current state value means in model you want to use somewhere else for validating, mergin etc…

2nd one is used when you want to retrive data from database for that particular model. it won’t point current value.

3rd one is almost same as 2nd one…

4th - $model = Yii::createComponent(‘User’);

5th - $model = Yii::createComponent(array(

‘class’ => ‘User’

));

mbi, can you also please explain when to use the 4th and 5th case scenario.

I mostly used 1 and 2…

1 to instantiate a new object to either use its elements for printing something out (labels etc) or to create a new record…by adding the attribute values and then

$model->save();

I use 2 to search for information.

findAll, findAllbyAttributes, findByPk etc… all come in handy depending on the situation.

Sometimes you can just use plain SQL if it’s a straightforward sql query where you won’t be confused about the syntax. Sql queries will mostly tend to be much faster than AR-records

I think that ‘new Model’ syntax and values return from find* methods gives us an object representing real data in the permanent storage (database).

Also, it is used for searching by calling new Model(‘search’) because the object will be assigned values to be able to call a search() method.

On the other hand, Model::model() and CActiveRecord::model(‘Model’) gives us a more lightweight object to call pseudo-static class methods like find*. They do not operate on any values in the object itself.

If anybody wants more details I suggest looking up the model() method and the constructor in the API docs and reading the source code and working out the differences.

Ok, thanks for all replies, I think now I know when to use each syntax as everyone told here. I have tried to see the CActiveRecord source but I think it’s quite deep to dig to understand how all things are happening, so let’s just use it :rolleyes: