Difference between #5 and #4 of Code style

Code style
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.

### Controller

The controller should contain code for collecting user input, retrieving models
from the database, and rendering views.

In a controller there should never**never** be:

 - HTML code: HTML should be in the view
 - SQL code: If needed, SQL should be in a modelmodel,
encapsulate in methods.
 - Field names: Field names should be in the view

Avoiding embedding field names allows you to change the database easily.

### Views

HTML code should only be in views.

Views should not**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

Models are used for collecting user inputs, and accessing the database.

In models there should not**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.

Write new article
  • Written by: zaccaria
  • Updated by: g3ck0
  • Category: Tips
  • Yii Version: 1.1
  • Votes: +30 / -1
  • Viewed: 18,539 times
  • Created on: Nov 9, 2010
  • Last updated: Nov 9, 2010
  • Tags: mvc