Yii 2.0 Best Practice: Information Hiding For Model Classes

Hello,

I’m new to Yii 2.0 developing and have a design question. I’ve created a user model for my user table holding some typical user data (username, email…). Now I want to list the user data in a view. Should I pass the user model directly to the view or should the view should only get access to an abstraction layer which forces a read-only access to the user model? I want to prevent the view (or other non-user-management-classes) from calling methods which writes to the db (like user->save). Is there any best practice for such an abstraction, or is my approach too theoretical?

Kind regards,

karl

Pass it to the view.

How would the end-user use that to re-update the model?

I think you are concerned about site users being able to use a view to run arbitrary code on the server?

The user can really only interact with the server via GET, POST, and ajax actions. If your page does not have any ajax functionality or forms I don’t see how this could be an issue.

Hi,

thank you for your answer. I’m not worried about the end-user, I’m more concerned about other developers using “my code”. Imaging delevoper A (me) implements the business logic (controllers/models) and developer B implements all UI stuff (views). If I simply let developer B access all of my internal models, some unwanted methods might be called (for example: ActiveRecord->save()).

How do other developer teams handle such situations? Do they only rely on good code documentation?

Kind regards,

karl

you could pass $model->attributes down to the view, your developer will only have read only access





return $this->render('view', ['user' => $model->attributes]);


// in your view

<?php echo $user['username']; ?>




Hi alirz23,

thank you for your answer, I think this is a good solution for me.

Kind regards,

karl