Widget is a part of Yii Framework, with the help of widget, we can create some functions like  post related, comments, search box,…

The best pros of using this yii widget is we can reuse the code in every page. And yii also has its own library to make a widget. Here is an example for making HotNewsWidget

Step 1: in component folder , create folder name views and HotNewsWidget.php

<?php 

class HotNewsWidget extends CWidget {
 public $listNews;

 public function init(){
  $this->listNews = News::model()->hot()->findAll();
 }
 public function getData(){
  return $this->listNews;
 }
 public function run(){
  $this->render('hotNewsWidget');
 }
}

?>

Step 2 : in views folder, create a php file name hotNewsWidget .

<div class="widget-header">
    <p>Hot news</p>
</div>
<div class="widget-news-detail">
  <ul>
   <?php
    foreach ( $this->getData() as $news) :
   ?>
   <li class="clearfix">
     <div class="widget-news-img">
         <img alt="Pictures of news" width="60" height="60" src="http://lorempixel.com/60/60/"/>
     </div>

     <div class="widget-news-content">
         <a href="#" title="Didauxa.net"><?php echo CHtml::encode($news->title_);?></a>
         <br/>
         <span>Date <?php echo  Yii::app()->dateFormatter->formatDateTime(
                        CDateTimeParser::parse(
                            $news->date_created_,
                            'yyyy-MM-dd hh:mm:ss'
                        ),'short',null
                    );
         ?>.</span>
     </div>
 </li>
 <hr/>
   <?php endforeach;?>
  </ul>
</div>

It’s done now, if you wanna call this widget, just call like normal widget in Yii.

<?php $this->widget('HotNewsWidget'); ?>