CodeIgniter is the correct way to create "block" elements in a web page
I have been looking for solutions for this problem for a while but have not seen any "correct mvc solution" for this. Hope I can explain my problem clearly enough for you guys.
-
I need to create a dynamic HTML block on my website. (for example, a block containing the latest comments on a user's blog).
-
I have a template view file (a file containing header, content container and footer) where I need to add some content and this block element.
The problem is, I don't want to duplicate this block of code on every controller. This is just silly and I'm sure there is a better way to do this than just duplicate the same stuff across all controller files?
I can add a view to another view just fine, but what worries me is how to create this dynamic content in this block view. I cannot call a controller from a view file, a controller from a file, or a controller model from a view file because I understand that this is just not the "mvc" way?
Anyone got any tricks or tips for this?
a source to share
I faced the same problem. I didn't want to duplicate this common logic in my action methods. I pushed this logic down to the base controller, but it was a little awkward.
I eventually came across an HMVC extension for CodeIgniter. This is a very good way to generate partial views. You create a module responsible for creating a partial. The module is coded using MVC, just like you would code your pages. This module can then be incorporated into your presentation.
If you've used ASP.NET MVC before, then it is similar to Html.RenderAction .
a source to share
As Zach pointed out, MY_Controller is great for creating global data.
One way to do this is to create "partial" views, which are just a view that contains everything it needs. Sometimes it's a bit of PHP, but for these special views, I don't mind making them dirty.
Another way is to associate a helper function with a view. Put all your PHP (cURL request for RSS fetch, caching, etc.) in a helper function, and then:
$this->load->view('partials/rss_feed');
The best way is to implement the Widgets system from PyroCMS . This is awesome!: D
a source to share
If you have multiple controllers that will draw this data, you can either use a model or extend the controller class with MY_Controller. This is well documented in the CodeIgniter User Guide.
If it's easy for many methods in one controller, you can put the logic in the Controllers constructor
After re-reading your post, I think your best bet is to extend the CodeIgniter Controller class with MY_Controller documented here.
a source to share