ApiService.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Api\Services;
  3. use App\Base\Library\Shorty;
  4. use App\Base\Services\ApiBaseService;
  5. use Illuminate\Support\Facades\Cache;
  6. class ApiService extends ApiBaseService
  7. {
  8. private $shorty;// 短地址服务
  9. public function __construct()
  10. {
  11. $this->shorty = new Shorty(config("app.domain"));
  12. }
  13. /**
  14. * 获取短地址
  15. */
  16. public function getShortUrl($urls)
  17. {
  18. $urls = is_array($urls) ? $urls : [$urls];
  19. $list = [];
  20. foreach ($urls as $url) {
  21. $key = "shortUrl_" . md5($url);
  22. $value = Cache::get($key, '');
  23. if ($value) {
  24. $list[$url] = $value;
  25. continue;
  26. }
  27. try {
  28. $list[$url] = $this->shorty->run($url);
  29. Cache::put($key, $list[$url], 86400 * 7);
  30. } catch (\Exception $e) {
  31. continue;
  32. }
  33. }
  34. if (count($urls) == 1) {
  35. return $list[$urls[0]];
  36. } else {
  37. return $list;
  38. }
  39. }
  40. }