Understanding Our Auto-Generated Code: Controller

May 20, 2013

In part 3 of the Yii tutorial, we’ll go through the auto-generated Controller code.

The UsersController class extends Yii’s Controller class. It handles all logic involving redirecting to specific views, e.g. list, view, admin, etc. All controllers generated by Gii extend the Controller class, and they have the same methods: filters, accessRules, actionView, actionCreate, actionUpdate, actionDelete, actionIndex, actionAdmin, loadModel, performAjaxValidation

We’ll discuss some of the functions briefly, one by one.

The filters method determines which actions should be run before or after any controller action is executed, e.g. ensuring that a user has permission before performing a create action. You can read more about filters here

The accessRules method defines rules by which users are allowed to access specific controller actions.

All methods beginning with ‘action’ represent actions that are accessible from the URL. For example, contents displayed on loading the url: http://localhost/StudentPortal/index.php/users/admin is determined by the function actionAdmin of the UsersController, same goes for http://localhost/StudentPortal/index.php/users/view/id/1, which is determined by actionView

You’ll notice that actionView accepts one parameter, id. This is the same string that is on the URL. More on this later.

The function loadModel is a utility function that returns the model having the given id.

The function performAjaxValidation does AJAX-based validation of a model. More on this later too.

And that’s it! We now have a basic understanding of our UsersController. Please don’t hesitate to ask any questions in the comments below. Next up, we’ll look at the views…