Putting Function To Be Called In View

Sometimes we need some complicated view to be displayed (such as generating complicated table). Most people suggest that in MVC the View must be as simple as possible (don't have too much loops, etc). So what we have to do is to hide away the complex code by putting it at somewhere else. The following are few places options to keep the function:

  1. We can add the function in the Model, so in the view file we just can call the model's method. The drawback of this method is model is not supposed to be put some viewing function. So it's not advisable to put the function related viewing or output result to the screen in there.
//File in the models/mymodel.php
class MyModel extends CActiveRecord{
    public function myFunction(){
        //do something...
    }
}
//File in the views/view.php
...
<?php MyModel::model()->myFunction(); ?>
...
  1. Use widget. We can create a class extends CWidget. In the View then we just need to call the widget function. Widget is more suitable when there is more than one view needed to display it.
//in the protected/components/mywidget
class MyWidget extends CWidget{
    public function init(){
        //do initializing...
    }
    public function run(){
        //render or echoing something...
    }
}
//in the view.php
...
<?php $this->widget('application.components.mywidget.MyWidget'); ?>
...
  1. Put the function to the controller. If the function only used in one view. Then it is better to putt into the Controller.
  1. Use the view file. Because the CController's render() and renderPartial() methods can return value instead displaying it, using view as the function is possible. That's mean we can put the function into certain view file (preferably in one folder with the caller if the caller only one). To make the render return value we must specified the third parameter to be 'true'.
//in the _view_function.php
....
<?php //echo something ?>
....
// in the view.php
...
<?php $this->renderPartial('_view_function', null, true); ?>
....
5 1
5 followers
Viewed: 43 682 times
Version: 1.1
Category: Tips
Tags: render, view
Written by: junxiong
Last updated by: junxiong
Created on: Dec 28, 2010
Last updated: 8 years ago
Update Article

Revisions

View all history

Related Articles