Home » YII Controllers

Controllers

In MVC structure, controllers role is to process the requests from the user and generate the responses. The incoming requests are analyzed by the controllers, passed onto models, models results are directed into views and finally a response is generated.

Controllers Action

Controller contains actions which are called by user to execute a request. A controller can have more than one request.

Following code is an example with two actions update and create in a controller file SiteController.php.

Look at the above code, action update (actionUpdate( )), it will first load the model according to requested id, then tries to include the new model instance using the request data and save the model. Then it will be redirected to view action with the model id. Otherwise, it will return the update action.

Action delete (actionDelete( )), it will load the model according to requested id,and then delete it. It will be redirected to the index action.

Routes

In Yii URL, you must have noticed there is a r. This r is the route.

For example: http://localhost/index.php?r=site/index

The route is site/index in the above example.

which consist of the following parts:

moduleID : It applies only when controller belongs to a non-application module.

controllerID : A string that identifies the controller among all controllers within a same module. In above example, it is site.

actionID : A string that identifies the action name among all actions in a controller. In above example, it is index.

Route format is:

ControllerID/ActionID

If belongs to a module, it takes the following format:

Next TopicControllers Action

You may also like