0 follower

Creating Portlet Architecture

Features like "the most recent comments", "tag cloud" are better to be implemented in portlets. A portlet is a pluggable user interface component that renders a fragment of HTML code. In this section, we describe how to set up the portlet architecture for our blog application.

Based on the requirements analysis, we need four different portlets: the login portlet, the "user menu" portlet, the "tag cloud" portlet and the "recent comments" portlet. These portlets will be placed in the side bar section of every page.

1. Creating Portlet Class

We define a class named Portlet to serve as the base class for all our portlets. The base class contains the common properties and methods shared by all portlets. For example, it defines a title property that represents the title of a portlet; it defines how to decorate a portlet using a framed box with colored background.

The following code shows the definition of the Portlet base class. Because a portlet often contains both logic and presentation, we define Portlet by extending CWidget, which means a portlet is a widget and can be embedded in a view using the widget() method.

class Portlet extends CWidget
    public $title; // the portlet title
    public $visible=true; // whether the portlet is visible
    // ...other properties...
    public function init()
            // render the portlet starting frame
            // render the portlet title
    public function run()
            // render the portlet ending frame
    protected function renderContent()
        // child class should override this method
        // to render the actual body content

In the above code, the init() and run() methods are required by CWidget, which are called automatically when the widget is being rendered in a view. Child classes of Portlet mainly need to override the renderContent() method to generate the actual portlet body content.

2. Customizing Page Layout

It is time for us to adjust the page layout so that we can place portlets in the side bar section. The page layout is solely determined by the layout view file /wwwroot/blog/protected/views/layouts/main.php. It renders the common sections (e.g. header, footer) of different pages and embeds at an appropriate place the dynamic content that are generated by individual action views.

Our blog application will use the following layout:

<?php echo CHtml::cssFile(Yii::app()->baseUrl.'/css/main.css'); ?>
<title><?php echo $this->pageTitle; ?></title>
<div id="sidebar">
...list of portlets...
<div id="content">
<?php echo $content; ?>

Besides customizing the layout view file, we also need to adjust the CSS file /wwwroot/blog/css/main.css so that the overall appearance would look like what we see in the blog demo. We will not go into details here.