Welcome Guest, Not a member yet? Register   Sign In
Menu from mysql in view
#1

[eluser]Unknown[/eluser]
Hi there,

if I want to load menu items from mysql it would be very comfortable to do it in my view file:
Code:
<ul>
&lt;?php
$query = $this->db->get('menu');

if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
  echo '<li>'. anchor($row->url, $row->text) .'</li>';
}
}
?&gt;
</ul>

But, according to MVC, it is bad practice, because all actions with data must be in model...

What would be the best way to do mysql menu?

Sorry for my bad english Smile
#2

[eluser]Krystian[/eluser]
try to
1. create model method that retrieve entries form menu table and returns an array

2. in Controller use this method and pass its results to the view

3. in view just use foreach loop to echo results

Smile
#3

[eluser]Jason Stanley[/eluser]
If this menu is in its own little snippet then I don't think you are doing a great deal wrong. Its a pretty simple menu. If you convert the database object to an array then you would still have essentially the same..

Code:
<ul>
&lt;?php
if (count($menu)
{
foreach ($menu as $item)
{
  echo '<li>'. anchor($item['url'], $item['text']) .'</li>';
}
}
?&gt;
</ul>

The main thing to change is to stop calling the model from the view. Instead pass the view file a variable containing the menu object.

I would only do more in the model if the navigation was more complex. If there were submenus etc which required a bit more logic I would create an array then probably a helper function to convert the array into html.
#4

[eluser]LuckyFella73[/eluser]
I would place the db query in a model for its a cleaner solution.
If you need the menu data in several controllers you will have to
repeat the code again and again.

If you place the db query in a model you can also set up a method
formatting the db result with needed html/ css and return the whole
html menu part (and send that to your view).
In case you have to change the html of your menu you have everything in one place.

Having the query in your view files would force you to edit up to maaany
lines in case something changes.




Theme © iAndrew 2016 - Forum software by © MyBB