Welcome Guest, Not a member yet? Register   Sign In
Using helpers to do dynamic elements (for example a menu) - is this good or bad practice?
#1

[eluser]loathsome[/eluser]
Hi there.

I'm currently developing a project, and this time we're using CI as our base. At every single page, we have a menu that fetches dynamic content from a database. The function to fetch content is located in the menu model.

Anyway, as the menu is going to be shown on every single page, we have placed the function to fetch this in a helper. So, in views/menu.php we're simply doing a
Code:
<?php $this->load->helper('menu'); ?>

The helper file loads up the model, fetches the content and displays the output.

The other solution would be to load the model, fetch content and pass it on to the view page in every single controller.

I appreciate your input here.
Thanks a lot!
#2

[eluser]JasonS[/eluser]
I would say that it is bad practice. Helpers are a collection of functions to 'help'. You appear to be using a helper to link to a model to get things going for you.

You could put your menu in a library. Then autoload the library.

In the menu file you would then have something like.

Code:
<?php $this->nav->mainMenu(); ?>

I would say that this is tidier. However, CI allows you flexibility to do whatever you are comfortable with.
#3

[eluser]wiredesignz[/eluser]
An autoloaded model is available to your views anyway, so why not just call the model directly from the view. and forget the helper.
#4

[eluser]loathsome[/eluser]
Great, thanks for your replies guys! I was already autoloading the model, weird how I didn't think of this at first.
#5

[eluser]xwero[/eluser]
If you call it on every page you can customize the CodeIgniter.php file. before this line
Code:
call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2));
You could add
Code:
// add menu data from menumodel to view variables
$CI->load->vars(array('menu'=>$CI->menumodel->menu()));
And in your views you can reach your menu data using $menu, which gives you the opportunity to overwrite the menu data if needed.
#6

[eluser]loathsome[/eluser]
-wrong-




Theme © iAndrew 2016 - Forum software by © MyBB