RecentCommentArticleView.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2020-02-20 10:13
  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 RecentCommentArticleView extends \yii\base\Widget
  14. {
  15. public $data = null;
  16. public $layout = "<ul>{%ITEMS%}</ul>";
  17. public $itemTemplate = '<li>
  18. <a href="{%URL%}" title="{%TITLE%}">
  19. <span class="thumbnail"><img src="{%IMG_URL%}" alt="{%TITLE%}"></span>
  20. <span class="text">{%TITLE%}</span>
  21. <span class="muted">{%CREATED_AT%}</span><span class="muted_1">{%COMMENT_COUNT%}{%COMMENT%}</span>
  22. </a>
  23. </li>';
  24. public function run()
  25. {
  26. $items = "";
  27. $linksModel = $this->getData();
  28. foreach ($linksModel as $model){
  29. /** @var Comment $model */
  30. $item = str_replace("{%URL%}", $url = Url::to(['article/view', 'id' => $model->id]), $this->itemTemplate);
  31. $item = str_replace("{%IMG_URL%}", $model->article->getThumbUrlBySize(125, 86), $item);
  32. $item = str_replace("{%TITLE%}", $model->article->title, $item);
  33. $item = str_replace("{%CREATED_AT%}", Yii::$app->getFormatter()->asDate($model->article->created_at), $item);
  34. $item = str_replace("{%COMMENT_COUNT%}", $model->article->comment_count, $item);
  35. $item = str_replace("{%COMMENT%}", Yii::t('frontend', ' Comments'), $item);
  36. $items .= $item;
  37. }
  38. return str_replace("{%ITEMS%}", $items, $this->layout);
  39. }
  40. private function getData()
  41. {
  42. if( $this->data === null ){
  43. /** @var CommentServiceInterface $commentService */
  44. $commentService = \Yii::$app->get(CommentServiceInterface::ServiceName);
  45. $this->data = $commentService->getRecentComments(8);
  46. }
  47. return $this->data;
  48. }
  49. }