Code style

You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#3)next (#5) »

  1. Where to put what
  2. Widgets

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 be:

  • HTML code: HTML should be in the view
  • SQL code: If needed, SQL should be in a model
  • 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 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 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

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.

29 0
7 followers
Viewed: 28 452 times
Version: Unknown (update)
Category: Tips
Tags: mvc
Written by: zaccaria
Last updated by: g3ck0
Created on: Nov 9, 2010
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles