Grampa
Grampa

Reputation: 1643

Yii Framework: Menu content that appears on every page

I'm using the Yii framework to develop a site that uses a 2-column layout. One column is the actual content, while the other is a menu with site links, some information about the logged in user and a list of the latest posts. The menu is present on all the pages, but it has no information that is related to the current page (or route).

Every time I render the menu I need to retrieve the list of latest posts and user-related data from the database. I'm not sure how it would be best to render this menu so that I don't repeat the code that fetches the data in every action on the site.

I have thought of a few approaches and I would like to know which one of them (if any) is the right way to handle this situation.

All of these methods work, but they all come with a few catches. I'm sure many sites are in the same situation and I'd like to see what the best option is.

Upvotes: 3

Views: 1441

Answers (1)

Paystey
Paystey

Reputation: 3242

You should be able to avoid most of the performance hit for re-requesting this data by simply caching the database results (either in memory or in files it's up to you and your set up). Here's a small, simple example:

$posts = Post::model()->cache(600)->with('comments')->findAll(array('blah=blahdyblah'));

This will cache the data returned for 10 minutes.

Here's a link to the Yii caching guide again only for completeness: Caching Guide

To actual get this data on every page, you would better off placing the code in your own widget, and having it called somewhere in the layout file.

The widget restrictions you list can be dealt with:

  • Firstly when the widget renders it will only render(), but without a layout. This is fine for most cases, but if you do want a page with just that on, say you want a real render(), then do exactly that, just create a view that only calls that widget.

  • Secondly, There's no reason widgets have to be entirely abstracted from your application and not use its data + models. Yes it is a very nice feature that they can be 'pluggable', but it doesn't mean they have to be, you're just using them to separate code.

  • Lastly, if you do want to use 'some' of the data from the widget but not all, or change it slightly, the methods and views you use within the widget should be built with just enough abstraction that you can use the pieces you need separately. A good way to do this is to make good use of scopes on ActiveRecords, mini view files, and using components for larger chunks of non-data logic.

Of course if you're running really on the limit of performance and need to trim thousandths of a second off your request time then you should be looking into view caching and using fragment caching of views:

Upvotes: 1

Related Questions