Welcome Guest, Not a member yet? Register   Sign In
define functions in views
#1

[eluser]Unknown[/eluser]
I have used CI for a few projects (very successfully!) and have run into this issue several times. I can never seem to find a definitive answer on it, so thought I would ask.

Is it acceptable to define functions in views? The response usually is no, they should be in a helper. However, I find situations when doing complicated formatting in a view that it makes sense to take a chunk of code out of a loop and put it in a function for organization sake. This code will never be reused outside of the view, so putting it in a helper doesn't really make sense.

The main issue I run into with this is that controller variables are not accessible in view functions. I get around this by using globals, but I have a feeling that is not advisable. I would be interested in opinions on this.

in controller:

Code:
$this->load->view('myview', array('mydata'=>$data));

in view:

Code:
GLOBAL $_mydata;
$_mydata = $mydata;

do_something_complicated();

function do_something_complicated()() {
   GLOBAL $_mydata;
   //do something with mydata
}

So...are functions in views ok?...and what is the best strategy for getting at controller vars?
#2

[eluser]CroNiX[/eluser]
Well, it depends. Normally it should be a helper, but if its not a general purpose function (that can be used over and over in different places) I don't think it really matters. In other words, if it can't be used anywhere else, it's kind of wasteful (inefficient) to have another file included when it can just be put in the view file where it is used and save the extra include.

But, why would you globalize the variables instead of just passing them to your function?

Code:
function do_something_complicated($_mydata)
{
  //blah blah boring overly-complex processing...

  return $formatted_awesome_clean_data;
}
#3

[eluser]Unknown[/eluser]
Thanks for the insight. Great point. In my particular case, it is three functions deep that I actually want to use $mydata (building a very complicated data table.) So it means including it as a parameter all the way down the stack until it is needed. The global seemed cleaner in that case. Passing as a parameter is much better if it is a single function call, and probably even makes more sense in my case, though kind of a hassle.
#4

[eluser]vbsaltydog[/eluser]
You could create a library with the three functions and make the vars class variables. That way they are available to all functions without needing to pass them back and forth.

This retains CI coding standards and is not just lazily setting the variables globally.




Theme © iAndrew 2016 - Forum software by © MyBB