fn_b/app/Providers/ArticleOrderLikesProvider.php

31 lines
1.1 KiB
PHP

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Cache;
use App\Services\CacheService;
//use App\Models\Categories;
class ArticleOrderLikesProvider extends ServiceProvider
{
public function boot(): void
{
// 只有渲染 components.order-likes 这个组件时,这段逻辑才会运行
View::composer('components.order-likes', function ($oView) {
// 从缓存拿数据,拿不到就触发一次更新(高标准兜底)
$aHotArticles = Cache::get(CacheService::CACHE_KEYS['article_order_likes']);
if (is_null($aHotArticles)) {
$aHotArticles = CacheService::updateOrderLikes();
}
$ids = collect($aHotArticles)->pluck('oArticle.id');
$visible = \App\Models\Articles::publicVisible()->whereIn('id',$ids)->pluck('id')->all();
$oView->with('oOrderLikes', array_values(array_filter($aHotArticles, fn($item)=>in_array($item['oArticle']['id'],$visible))));
});
}
}