Welcome Guest, Not a member yet? Register   Sign In
Load views in Controller or Model?
#1

[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...
#2

[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.
#3

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

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

[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));




Theme © iAndrew 2016 - Forum software by © MyBB