Is There A Better Way To Do This (Model-User Relations)

Hello and thanks in advance for reading this topic. I am an experienced PHP dev but pretty new to Yii and MVC frameworks in general. I have gone through several tutorials and made a few small apps using Yii but am still discovering the best ways to do certain things. I really like how simple it is to associate models using the relations() method and then access that data but my question is regarding when I am inserting or loading data and how I verify it belongs to a certain user. Associating a user id with a record seems pretty straightforward, I just add an extra line to the actionCreate method generated by gii after the $model->attributes statement:


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

$model->user_id = Yii::app()->user->id;

Is this the correct way to do it or is there a more accepted/standard way to make sure the user_id field of my models is populated with the user who created a record?

Secondly, when I’m using the view/update/delete actions I want to make sure they are only accessible by the user who created them. Gii auto-generates the function loadModel in the controllers which has no validation so I ended up adding a new function to the Controller.php class in the Components directory called loadModelByUser:


public function loadModelByUser($modelname,$id)

{

	$model = $modelname::model()->findByAttributes(array('id'=>$id,'user_id'=>Yii::app()->user->id));

	if($model===null)

		throw new CHttpException(404,'The requested page does not exist.');

	return $model;

}

Again, is there a better way to do this built into Yii which I missed in the tutorials?

First question - that is perfectly fine!

Second question - read the Guide regarding scopes. Instead of creating a separate loadModel you may want to look at defaultScope functionality. This will provide an ‘automatic’ WHERE condition to all your queries.

On the first question actually to make sure you always populate the model with the userID of the current user before saving you can also define a beforeSave() function in the model to do it every time, instead of writing code in the controller action. Either way is ok.

Thank you for the response. Good idea about using the beforeSave function I had forgotten about that. I will also check out the defaultScope function.