function inside a view in codeigniter

十年热恋 提交于 2020-05-15 04:52:09

问题


i'm a newbie in ci, can anyone help me or give some suggestions in my code and best practice? i have a foreach statement that require to use a function for displaying a huge data. here's my sample code of view. Thank you in advance

 foreach($data->result() as $d){

    if($d->condi){
       $sample =   myfunction($d->value1, $d->value2, $value->3);
    } 
    else{ 
         $d->otherdisplay;
            if($d->condition2){
            $sample =   myfunction($d->value1, $d->value2, $value->3);
            }
    }
}
function myfunction($a,$b,$c){
       /*do something;*/

}

回答1:


it depends , anyway these kind of methods should be in controllers or in libraries, it depends if your method can be called from browser or not.

If you want to use some method that you need to makesome routine action use a

library or an helper

If you want to use a web page method use that in controller

 Model = SQL and db stuffs

 Controller = all the php stuffs + data returned from Model

 View = html/js + data returned from Controller

Check How to create Own libraries in CI




回答2:


A better approach would be to create a helper file in CI, and put this function in the helper file. Create you helper file in 'application/helpers' directory Then include this helper in the controller which is calling this view, Like

$this->load->helper('name');

And now, you can use all the functions of the helper file directly in your view without any codeigniter instance.

Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category.

http://ellislab.com/codeigniter/user-guide/general/helpers.html




回答3:


You should put your functions in the controller classes as much as possible (or somewhere else, as long as you call them from the controller). Parse your data there and then loop through it in the view. This keeps your code clean and organized and keeps true to the MVC principle.



来源:https://stackoverflow.com/questions/15807145/function-inside-a-view-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!