I’m about to write a admin panel for my CMS written in CodeIgniter. There will be some user information visible at all time – both in the layout’s header section and the sidebar. I’m used to do it in a way that I personally hope and think could be done a lot easier, since I’m tired of sending the same parametres to the view over and over again, when it’s dynamic data that needs to be displayed on every page anyways (such as unread messages, username, name, status, etc).
I’ll need controllers and models, I know that, but do I have to pass, just for an example, the user’s username, unread messages etc. every time I need to load a view? Should I do some kind of library for this?
Now my question is: How would I do it when it comes to best practice and for making it easy to maintain in the future?
I hope my question is understandable 🙂
Personally, I would extend the Controller library (create a MY_Controller by following the guidance at the bottom of Creating Libraries at codeigniter.com).
You would use your model etc as normal. Then you would create a private function in your MY_Controller class to get the relevant “global” data and call
which would make the data available to all views called from that point on as
$everywhere_data. Then add a reference to that function in the constructor of MY_Controller, perhaps with a conditional checking for the user to be actually logged in.If it’s complex to collect and get all that data, you might write a library to handle it for you, but the ‘controller’ part would still be done by MY_Controller: i.e. to get the data and then use load->vars() to publish it to the view.
As a quick and untested example, MY_Controller would start something like as follows:
Note that things like
_logged_in_userid()would access the session for you (e.g.return $this->session->userdata('logged_in_userid');), and_get_user()would access the relevant models.Finally, you would have a view that accesses
$logged_in_username(oreverywhere_datain my first example) which you would call into your headers etc. This leaves your normal controllers uncluttered so that they can focus on delivering their specific functionality, stops you rewriting your code several times AND maintains the MVC ideals.