CActiveRecord Instantiation Context

Hello,

Say I have a CActiveRecord derative called MyModel.

I can do a couple of things with it:




$models = MyModel::model()->samplenamedscope()->findAll();

$model = new MyModel(); $model->attributes = $_POST; $model->save();



The first, MyModel::model(), is like instantiating a MyModel in a "static" context. In the above example we: get the model, apply a scope to it to change CDbCriteria, then findAll() to return a bunch of individual models.

The second, $model = new MyModel(), is instantiating MyModel in a "singular" context. Everything you do on that $model represents actions on a single record.

I’m writing a CActiveRecordBehavior that provides a function; say, call it sync().

You can call the same function from these two different contexts, eg.




// "Static" (sync() everything matched by the CDbCriteria.)

MyModel::model()->mysamplescope()->sync();


// "Singular" (sync() just this record.)

$model=new MyModel(); $model->title = 'foobar'; $model->save(); $model->sync();



My question:

From my CActiveRecordBehavior, how do I tell if sync() is being called via ::model(), or from a single record’s model?

Answer thanks to rawtaz on IRC:

$scenario, and the results of calling "MyModel::model()" vs "new MyModel()":




$static = MyModel::model();

var_export($static->scenario); // ---> '' (blank)


$models = MyModel()->myscope()->findAll();

var_export($static->scenario); // ---> '' (still blank)


$model = new MyModel();

var_export($static->scenario); // ---> 'insert'



tl;dr

  • MyModel::model() objects have blank $scenario member vars.

  • new MyModel() objects have non-blank $scenario member vars (eg. ‘insert’, ‘update’).