LatestCommentView.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2020-02-20 01:08
  7. */
  8. namespace frontend\widgets;
  9. use Yii;
  10. use common\models\Comment;
  11. use common\services\CommentServiceInterface;
  12. use yii\helpers\Url;
  13. class LatestCommentView extends \yii\base\Widget
  14. {
  15. public $data = null;
  16. public $layout = "<ul>{%ITEMS%}</ul>";
  17. public $itemTemplate = '<li>
  18. <a href="{%HREF%}" title="">
  19. <img data-original="{%AVATAR%}" class="avatar avatar-72" height="50"width="50" src="" style="display: block;">
  20. <div class="muted">
  21. <i>{%NICKNAME%}</i>&nbsp;&nbsp;{%RELATIVE_TIME%}
  22. ({%CREATED_AT%}) {%SAID%}
  23. :<br>{%CONTENT%}</div>
  24. </a>
  25. </li>';
  26. public function run()
  27. {
  28. $items = "";
  29. $models = $this->getData();
  30. foreach ($models as $model){
  31. /** @var Comment $model */
  32. $item = str_replace("{%HREF%}", Url::to(['article/view', 'id' => $model->aid, '#' => 'comment-' . $model->id]), $this->itemTemplate);
  33. $item = str_replace("{%AVATAR%}", Yii::$app->getRequest()->getBaseUrl() . "/static/images/comment-user-avatar.png", $item);
  34. $item = str_replace("{%NICKNAME%}", $model->nickname, $item);
  35. $item = str_replace("{%RELATIVE_TIME%}", Yii::$app->getFormatter()->asRelativeTime($model->created_at), $item);
  36. $item = str_replace("{%CREATED_AT%}", Yii::$app->getFormatter()->asTime($model->created_at), $item);
  37. $item = str_replace("{%SAID%}", " " . Yii::t('frontend', 'said'), $item);
  38. $item = str_replace("{%CONTENT%}", $model->content, $item);
  39. $items .= $item;
  40. }
  41. return str_replace("{%ITEMS%}", $items, $this->layout);
  42. }
  43. private function getData()
  44. {
  45. if( $this->data === null ){
  46. /** @var CommentServiceInterface $commentService */
  47. $commentService = \Yii::$app->get(CommentServiceInterface::ServiceName);
  48. $this->data = $commentService->getRecentComments();
  49. }
  50. return $this->data;
  51. }
  52. }