Hi, if I have a page on my site where i have to show 4 or 5 snippets (news feeds, event feed etc), all relating to different data (in different models and db tables), then what is a sensible way to handle the generation of the snippet content and layout? i could use a single snippet controller which contains static functions which each return a view populated with the relevant data. But each function in this snippet controller will be interacting with different data/models, so i'm not sure how OOP this is. Or, I could just add a static function to each of the controllers which are dealing with each associated set of data - e.g in a News_Controller, as well as functions to show all news items, individual news items etc, i could add a static function to generate the news feed by simply returning the view I need. I think this approach might work, as i don't want to instantiate an object for these simple snippets, so having static functions in the relevant controllers makes a bit of sense. Bit of a stream of consciousness here, but am i making any sense?!
You can architect your MVC pattern to provide a mechanism for allowing data that has been set to be returned as an array. For instance, normally a web request to /news/feed/
would result in pertinent data being set and subsequently passed to a view. In addition to web requests, the system should also allow a controller to make such a request, i.e., $vars = $this->call('/news/feed/');
The system will recognize the internal request and return the set vars rather than invoking a view.
This allows you to keep your controllers and models cohesive.
You may want to look into Hierarchical Model-View-Controller (HMVC). It's especially suited to making pages with snippets. I believe Kohana implements it.
Basically, you have multiple Model-View-Controller triads each responsible for each snippet. So you could have a controller to access the News database and load a variety of small views for different types of news displays.
Many frameworks have some notion of "partials", which are typically used for this kind of thing.
Since these partials are generally read-only, and are often displayed on every page (or some well-defined set of pages), you can approach them without thinking in terms of controllers like you would for a page.
In other words -- remember that it's fine if your view/layout code talks directly to your models, as long as it's only interrogating them.
I do things like this all the time:
layout.php:
<div id="newsWidget">
<?PHP $news = Model_News::latest(); ?>
<?PHP foreach($news as $newsitem): ?>
<!-- output some news headlines -->
<?PHP endforeach; ?>
</div>
Model_News::latest() might implement some caching, etc, since this is layout code and I probably don't want to hit the db on every request.
No controller-bloat necessary!