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:
//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(); ...
//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); ....
Total 2 comments
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 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)...
and from the view you call it like
Leave a comment
Please login to leave your comment.