Performance of automatically generated controller code

Hope I got this right :rolleyes:

The automatically generated actionUpdate code actually loads a model before updating it and reloads it again after update when the ‘show’ action is executed as follows:

[indent]




public function actionUpdate()

{

	$model=$this->loadaddressbook();

	if(isset($_POST['addressbook']))

	{

		$model->attributes=$_POST['addressbook'];

		if($model->save())

			$this->redirect(array('show','id'=>$model->id));

	}

	$this->render('update',array('model'=>$model));

}



[/indent]

Why not use the updateByPk as below. This only loads the model once when actually 'show’ing it.

[indent]




public function actionUpdate()

{

	if(isset($_POST['addressbook']))

	 {

 		if(addressbook::model()->updateByPk ($_GET['id'], $_POST['addressbook']))

		$this->redirect(array('show','id'=>$_GET['id']));

	}

	$this->render('update',array('model'=>$this->loadaddressbook()));

}



[/indent]

Same thing for the actionDelete. Why do we load a model if it is going to be deleted as follows:

[indent]




public function actionDelete()

{

	if(Yii::app()->request->isPostRequest)

	{

		// we only allow deletion via POST request

		$this->loadaddressbook()->delete();

		$this->redirect(array('list'));

	}

	else

		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

}



[/indent]

This can be done without actually loading the model using the deleteByPk

[indent]




public function actionDelete()

{

	if(Yii::app()->request->isPostRequest)

	{

		// we only allow deletion via POST request

		addressbook::deleteByPk($_POST['id']);

		$this->redirect(array('list'));

	}

	else

		throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

}



[/indent]

As a side note, while the deleteByPk can be called as a statis ‘::deleteByPk’ function, the updateByPk function throws a AddressbookController does not have a method named “getCommandBuilder” exception when called statically ‘::updateByPk’

/Kaf

When updating, you still need to validate if the inputs are correct, which requires the existence of a model instance.

Same for deletion, before you perform the deletion you want to verify the ‘id’ is correct. Of course, this can be slightly optimized without loading the model first.

For create/update/delete operations, performance is not very crucial because it usually has much lower frequency than reading operations. It is more important in these cases to ensure the correctness and safety of these operations.

When calling deleteByPk (or updateByPk), you should use ModelClass::model()->deleteByPk() rather than calling it in the static way.

Not to mention, Yii lack of "transaction" usage makes this process safer against overwriting concurrent updates.

Thanks!

That’s what an enthusiastic beginner does :P