I have a menu on my page that is loaded on every page. The menu data is fetched from the database through a model. My first thought was to call the model from the controller, and then pass it to the view on every page. But that results in “messy” code, if i ever forget to pass the menu data to the view, it will result in an ugly error (or just no menu items).
So i came up with the solution of fetching the menu items through a helper, and then just call the helper function from the view. It makes more sense, because i only have the code in one place (the menu view).
My views are set up in this way: Controller calls “page” view which then loads the header view, menu view, the appropriate content view, and lastly the footer view. The helper is only called from one place, the menu view.
Normally you can’t even load models from helpers, but i did a workaround using $i = get_instance(); and then loading the model through that instance; $i->load->model().
I have a feeling this is not the way to go, but are there any better ways?
Edit: To put it in a better way:
I want:
view -> get data -> display
not:
controller -> get data -> pass to view -> display
I’m just not sure if that’s “Ok” to do, since it disregards the MVC model completely.
I think that the solution is easier than you think.
If now you’re doing something like this in your helper:
You could just change the function to accept input like this and still follow the MVC pattern.
Helper
Model:
Does this make sense?
Edit:
This is the way I did it on one of the projects:
I extended my standard controller. Within the constructor of that controller I called the model and grabbed the data:
Within a view
nav.php:This way the MVC is intact, but I dont have to worry about passing variables.
EDIT 2
How to extend the standard controller:
Create a file
MY_Controller.phpinapplication/coreWhen you create a new controller, you extend
MY_Controllerinstead ofCI_Controllerlike this: