You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.
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:
- 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(); ?>
...
- 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'); ?>
...
- Put the function to the controller. If the function only used in one view. Then it is better to putt into the Controller.
- 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); ?>
....
widget
If the view code/function will be used in more than one view... then creating a widget is the best way, but if the function is to be used only by that view/controller than you can put the function in the controller (better than in the model)...
class DocumentController extends Controller { public function testXY() { return "complex display"; } }
and from the view you call it like
<?php echo $this->testXY(); ?>
Calling a controller method from a view
It's a bad practice to call controller methods from view files. The goal is to decouple controllers and views and by doing it you're creating an unnecessary coupling.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.