CodeIgniter Forums
Keeping models out of views - applying a function to a result array - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Keeping models out of views - applying a function to a result array (/showthread.php?tid=20426)



Keeping models out of views - applying a function to a result array - El Forum - 07-09-2009

[eluser]mattpointblank[/eluser]
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?

Thanks
Matt


Keeping models out of views - applying a function to a result array - El Forum - 07-09-2009

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


Keeping models out of views - applying a function to a result array - El Forum - 07-09-2009

[eluser]TheFuzzy0ne[/eluser]
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.


Keeping models out of views - applying a function to a result array - El Forum - 07-09-2009

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