这个主要描述的就是如何写一个自定义组件。
首先,建立frontend/widgets/ 目录,这个目录主要存放在前台使用的所有组件。
一个组件主要包括一个以Widget结尾的php文件和views里面的视图文件。
ChatWidget.php 代码
<?php
namespace frontend\widgets\chat;
use frontend\models\FeedForm;
use Yii;
use yii\bootstrap\Widget;
class ChatWidget extends Widget
{
public function run()
{
$feed = new FeedForm();
$data['feed'] = $feed->getList();
return $this->render('index', ['data' => $data]);
}
}
涉及到的FeedForm这个model层的代码,由于里面只用到了getList方法,其他的方法已经省略
<?php
namespace frontend\models;
use common\models\FeedsModel;
use yii\base\Model;
use Yii;
class FeedForm extends Model
{
public $content;
public $_lastError;
public function rules()
{
return [
['content', 'required'],
['content', 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'content' => '内容'
];
}
public function getList()
{
$model = new FeedsModel();
$res = $model->find()->limit(10)->with('user')->orderBy(['id' => SORT_DESC])->asArray()->all();
return $res?:[];
}
}
然后在ChatWidget.php文件中&#x