Skip to content

Commit

Permalink
推荐资源列表
Browse files Browse the repository at this point in the history
  • Loading branch information
liyu001989 committed Aug 7, 2020
1 parent 13c28a7 commit 89e00a5
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 2 deletions.
18 changes: 18 additions & 0 deletions app/Http/Controllers/Api/LinksController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace App\Http\Controllers\Api;

use App\Models\Link;
use Illuminate\Http\Request;
use App\Http\Resources\LinkResource;

class LinksController extends Controller
{
public function index(Link $link)
{
$links = $link->getAllCached();

LinkResource::wrap('data');
return LinkResource::collection($links);
}
}
17 changes: 17 additions & 0 deletions app/Http/Resources/LinkResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class LinkResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'link' => $this->link,
];
}
}
4 changes: 2 additions & 2 deletions app/Models/Link.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ class Link extends Model
protected $fillable = ['title', 'link'];

public $cache_key = 'larabbs_links';
protected $cache_expire_in_seconds = 1440 * 60;
protected $cache_expire_in_minutes = 1440;

public function getAllCached()
{
// 尝试从缓存中取出 cache_key 对应的数据。如果能取到,便直接返回数据。
// 否则运行匿名函数中的代码来取出 links 表中所有的数据,返回的同时做了缓存。
return Cache::remember($this->cache_key, $this->cache_expire_in_seconds, function(){
return Cache::remember($this->cache_key, $this->cache_expire_in_minutes, function(){
return $this->all();
});
}
Expand Down
3 changes: 3 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@
// 某个用户的回复列表
Route::get('users/{user}/replies', 'RepliesController@userIndex')
->name('users.replies.index');
// 资源推荐
Route::get('links', 'LinksController@index')
->name('links.index');

// 登录后可以访问的接口
Route::middleware('auth:api')->group(function() {
Expand Down

0 comments on commit 89e00a5

Please sign in to comment.