CodeIgniter - the right way to create "block" elements on web page
I've been searching for a solutions for this problem a while but haven't seen any "valid mvc" solution for this. I hope I can explain my problem clearly enough for you guys.
I need to create a dynamic block of HTML on my website. (eg. a block containing user's latest blog comments).
I have a template view file (a file containing header, content container and a footer) where I need to add some content AND this block element.
The problem is that I don't want to duplicate this block code on every controller. It just feels stupid and I'm sure there's a better way to do this than just duplicating same stuff all over again on all the controller files?
I can add view inside another view just fine, but what bugs me is how to actually generate that dynamic content to this block's view-file. I can't call controller from view file, controller from controller filem or model from view file because what I understand that 开发者_如何学Cjust isn't the "mvc" way?
Anyone got any tricks or tips for this?
As Zack has pointed out, MY_Controller is great for creating global data.
One way I do this is to create "partial" views, which are just a view that contains everything it needs. Sometimes that is a little bit of PHP but for these special views I don't mind making them dirty.
Another way is to pair a helper function with a view. Put all your PHP (cURL request to fetch RSS, caching, etc) in the helper function then:
$this->load->view('partials/rss_feed');
The best way is to implement the Widgets system from PyroCMS. That thing is awesome! :D
I ran into the same problem. I didn't want to duplicate this common logic across my action methods. I was moving this logic up to the base controller but it felt a bit clunky.
I eventually stumbled upon the HMVC extension to CodeIgniter. Its a really nice way of generating partial views. You create a module responsible for generating the partial. The module is coded in an MVC way, just like you would code your pages. This module can then be included in your view.
If you've used ASP.NET MVC before, its similar to using Html.RenderAction.
If you have multiple controllers that will draw this data, you could either use a model, or extend the Controller class with MY_Controller. This is documented well in the CodeIgniter user guide.
If it is just for many methods in the same controller, you can put the logic in the Controllers constructor
After re-reading your post, I think the best thing for you to do is to extend CodeIgniter's Controller class with MY_Controller documented here.
精彩评论