· 4 years ago · Sep 08, 2021, 05:34 PM
1<?php
2
3namespace App\Http\Controllers;
4
5use Exception;
6use Illuminate\Database\Eloquent\Model;
7use Illuminate\Database\Query\Builder;
8use Illuminate\Support\Facades\DB;
9use Psr\Log\LoggerInterface;
10use Psr\SimpleCache\CacheInterface;
11use Psr\SimpleCache\InvalidArgumentException;
12use SomeAPI;
13
14class SomeController extends Controller
15{
16 /**
17 * @var LoggerInterface
18 */
19 private LoggerInterface $logger;
20
21 /**
22 * @var CacheInterface
23 */
24 private CacheInterface $cache;
25
26 /**
27 * SomeController constructor.
28 * @param LoggerInterface $logger
29 * @param CacheInterface $cache
30 */
31 public function __construct(LoggerInterface $logger, CacheInterface $cache)
32 {
33 $this->logger = $logger;
34 $this->cache = $cache;
35 }
36
37 /**
38 * @param $key
39 * @return Model|Builder|mixed|object
40 * @throws InvalidArgumentException
41 */
42 public function GetData($key)
43 {
44 $data = $this->cache->get($key);
45 if ($data === null) {
46 $data = DB::table('mytable')->where('key', $key)->first();
47 if ($data === null) {
48 $this->logger->warning($key . ' is not found in database');
49 $data = SomeAPI->get($key);
50 if ($data === null){
51 $this->logger->warning($key . ' API did not return a value');
52 throw new Exception('Invalid key');
53 } else {
54 $data = DB::table('mytable')->insert($data);
55 $this->logger->info($data . ' is written in database');
56 $this->cache->set($key, $data, 900);
57 return $data;
58 }
59 } else {
60 $this->cache->set($key, $data, 900);
61 return $data;
62 }
63 } else {
64 return $data;
65 }
66 }
67}
68