CodeIgniter Forums
Load views in Controller or Model? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Load views in Controller or Model? (/showthread.php?tid=58210)



Load views in Controller or Model? - El Forum - 05-23-2013

[eluser]flacznik[/eluser]
Yesterday i red a book where the writer advise to load a view inside a model. Then simply call the function in controller like to show the page:

Code:
$this->load->model('display');
$this->display->mainpage($data);

The question is - which way is more proper, to load the views inside controller or model? In my opinion is quite interesting to build the view inside a model...


Load views in Controller or Model? - El Forum - 05-24-2013

[eluser]Pert[/eluser]
I've stared using magic method __toString to handle at least some parts of views.

So lets say I have library that handles form HTML, input, output, etc.

If I do <?= $form ?> it will actually echo out the HTML code.

Or I have a library that handles status messages (your content has been saved), I can set the actual message, and type (warning, success) and again, echo the object to get HTML.

You could also implement a "draw" function that will return right view.

Something like $news->draw('article') to get full article view, and $news->draw('headline') to get headline HTML for homepage.

If your model data could have multiple views that are only used limited times in limited controllers, you might want to load views from controllers, but if you call same view logic alot from different controllers, it might be easier to add quick routine to model that handles views, so controller code is shorter.

Always look where you would copy-paste same code alot, it's usually the place to automate things with helper methods.


Load views in Controller or Model? - El Forum - 05-24-2013

[eluser]flacznik[/eluser]
Briliant replay. Thank you...


Load views in Controller or Model? - El Forum - 05-25-2013

[eluser]jairoh_[/eluser]
the propery way is in the controller, models are designed for the backend databases' queries and etc. Smile


Load views in Controller or Model? - El Forum - 05-29-2013

[eluser]Pert[/eluser]
[quote author="jairoh_" date="1369545456"]the propery way is in the controller, models are designed for the backend databases' queries and etc. Smile[/quote]

Sure, but you could also cut out some of manual work loading views and choosing what view to show, specially when you have to load the same views in multiple controllers and/or methods.

Code:
$shopping_cart->draw('mini-cart');

just seems slightly more elegant than

Code:
if ($user->type === 'VIP')
   $view_file = 'shopping-cart/vip-mini-cart';
else
   $view_file = 'shopping-cart/mini-cart';
$this->load->view($view_file, array('shopping_cart' => $shopping_cart));