FriendlyLinkView.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2020-02-20 00:49
  7. */
  8. namespace frontend\widgets;
  9. use common\models\FriendlyLink;
  10. use common\services\FriendlyLinkServiceInterface;
  11. class FriendlyLinkView extends \yii\base\Widget
  12. {
  13. public $data = null;
  14. public $layout = "{%ITEMS%}";
  15. public $itemTemplate = "<a target='_blank' href='{%URL%}'>{%NAME%}</a>";
  16. public function run()
  17. {
  18. $items = "";
  19. $linksModel = $this->getData();
  20. foreach ($linksModel as $model){
  21. /** @var FriendlyLink $model */
  22. $item = str_replace("{%URL%}", $model->url, $this->itemTemplate);
  23. $item = str_replace("{%NAME%}", $model->name, $item);
  24. $items .= $item;
  25. }
  26. return str_replace("{%ITEMS%}", $items, $this->layout);
  27. }
  28. private function getData()
  29. {
  30. if( $this->data === null ){
  31. /** @var FriendlyLinkServiceInterface $friendlyLinkService */
  32. $friendlyLinkService = \Yii::$app->get(FriendlyLinkServiceInterface::ServiceName);
  33. $this->data = $friendlyLinkService->getFriendlyLinks();
  34. }
  35. return $this->data;
  36. }
  37. }