Putting Function To Be Called In View

You are viewing revision #2 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.

next (#3) »

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 adviseable 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. 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: 51 824 times
Version: Unknown (update)
Category: Tips
Tags: render, view
Written by: junxiong
Last updated by: junxiong
Created on: Dec 28, 2010
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles