创建小部件

小部件是视图中可复用的部分,它不仅会渲染一些数据,而且还能依赖于一些逻辑。它甚至可以从模型中获取数据,并使用它自己的视图,所以它就像一个简化的可复用的模块。

下面我们来创建一个小部件,它会使用Google API画一个饼状图。

准备

按照官方指南http://www.yiiframework.com/doc-2.0/guide-start-installation.html的描述,使用Composer包管理器创建一个新的yii2-app-basic应用。

如何做…

  1. 创建widgets目录,并添加ChartWidget类:
  1. <?php
  2. namespace app\widgets;
  3. use yii\base\Widget;
  4. class ChartWidget extends Widget
  5. {
  6. public $title;
  7. public $width = 300;
  8. public $height = 200;
  9. public $data = [];
  10. public $labels = [];
  11. public function run()
  12. {
  13. $path = 'http://chart.apis.google.com/chart';
  14. $query = http_build_query([
  15. 'chtt' => $this->title,
  16. 'cht' => 'pc',
  17. 'chs' => $this->width . 'x' . $this->height,
  18. 'chd' => 't:' . implode(',', $this->data),
  19. 'chds' => 'a',
  20. 'chl' => implode('|', $this->labels),
  21. 'chxt' => 'y',
  22. 'chxl' => '0:|0|' . max($this->data)
  23. ]);
  24. $url = $path . '?' . $query;
  25. return $this->render('chart', [
  26. 'url' => $url,
  27. ]);
  28. }
  29. }
  1. 创建widgets/views/chart.php视图:
  1. <?php
  2. use yii\helpers\Html;
  3. /* @var $this yii\web\View */
  4. /* @var $url string */
  5. ?>
  6. <div class="chart">
  7. <?= Html::img($url) ?>
  8. </div>
  1. 创建一个ChartController控制器:
  1. <?php
  2. namespace app\controllers;
  3. use yii\base\Controller;
  4. class ChartController extends Controller
  5. {
  6. public function actionIndex()
  7. {
  8. return $this->render('index');
  9. }
  10. }
  1. 添加views/chart/index.php视图:
  1. <?php
  2. use app\widgets\ChartWidget;
  3. use yii\helpers\Html;
  4. /* @var $this yii\web\View */
  5. $this->title = 'Chart';
  6. $this->params['breadcrumbs'][] = $this->title;
  7. ?>
  8. <div class="site-about">
  9. <h1><?= Html::encode($this->title) ?></h1>
  10. <?= ChartWidget::widget([
  11. 'title' => 'My Chart Diagram',
  12. 'data' => [
  13. 100 - 32,
  14. 32,
  15. ],
  16. 'labels' => [
  17. 'Big',
  18. 'Small',
  19. ],
  20. ]) ?>
  21. </div>
  1. 现在尝试运行这个动作。你应该能看到一个饼状图,如下所示:

创建小部件 - 图1

  1. 你可以展示不同尺寸和数据集的图。

工作原理…

和其它类型的扩展一样,我们创建一些可以配置的公共属性,在调用一个小部件时使用它的widget方法。在这个例子中,我们配置了标题、数据集和数据标签。

小部件的主方法是run()。在我们的小部件中,我们生成一个URL,并渲染小部件视图,它使用Google charting API来打印<img>标签。

参考