Where to put what ¶
Often, when writing widgets or editing Yii code, it is unclear whether or not the code is following the MVC pattern.
Here are a few suggestions to help detect the most obvious style errors.
The controller should contain code for collecting user input, retrieving models from the database, and rendering views.
In a controller there should never be:
- HTML code: HTML should be in the view
- SQL code: If needed, SQL should be in a model, encapsulate in methods.
- Field names: Field names should be in the view
Avoiding embedding field names allows you to change the database easily.
HTML code should only be in views.
Views should not contain:
- User input (e.g. $_GET and $_POST): Input should be collected in models in the controllers, never in views.
- SQL: When needed, it is best to create a function in the model
The fewer PHP operations there are in the views, the better it is. Instead of concatenating two fields, it is better to write a getter method, so you can reuse it in other views.
Models are used for collecting user inputs, and accessing the database.
In models there should not be:
- User input ($_GET, $_POST): You should write a function that will be called in the controller.
- HTML: HTML should be in a view
Widgets have a behaviour similar to controllers. If a widget is supposed to create a lot of HTML, it is better to create a view file for it.