Welcome Guest, Not a member yet? Register   Sign In
Keeping models out of views - applying a function to a result array

Hi all,

I'm looping through a set of database rows in my view. Simple enough. However, I want to apply a function to clean up dates and work out date differences inside this loop. I've put my function to do this in my model, but I'm calling the function from inside the view, which I've read is bad practice. I'm trying to keep as little code as possible in my views, so I'd definitely like a better method. How does everyone else do things like this? I could loop through my result array in the model before returning it and apply the function there, but then I have to loop through my resultset twice (once in the model to apply the function, and once in the view to display it). Is there a better way that hasn't occurred to me?


[eluser]GSV Sleeper Service[/eluser]
this sounds like it would be better off as a helper

Hi, Matt!

There are no rules against making calls to models in your views, but some people (like myself) to prefer avoid it, since technically $this just happens to link to the CodeIgniter super object (as the view is processed within it's scope). I think that what's considered bad practice is using $this within your view.

If I were in your position, I'd export the formatting method to a helper, and use that. format($some_data) looks nicer to me than $this->some_model->format($some_data), but that's just my personal preference. Of course, if you're only calling on this method from within a loop, it shouldn't really make any difference.

Thanks guys, makes sense to do it that way. Glad to know my suspicions about using $this in views being bad practice were right!

Theme © iAndrew 2016 - Forum software by © MyBB