我正在使用Laravel开发应用程序时遇到一些困难。
我想使用
事件和监听器删除
并重建对象的缓存。
以下是代码:
app\Events\CampaignEvent.php
namespace App\Events;
use Illuminate\Queue\SerializesModels;
class CampaignEvent extends Event
{
use SerializesModels;
public $user_id;
public $cache_keys;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($user_id, $cache_keys)
{
$this->user_id = $user_id;
$this->cache_keys = $cache_keys;
}
}
app\Listenters\CampaignListener.php
<?php
namespace App\Listeners;
use App\Events\CampaignEvent;
use Cache;
use Log;
use App\BrandCampaign;
class CampaignListener
{
/**
* Handle the event.
*
* @param CampaignEvent $event
* @return void
*/
public function handle(CampaignEvent $event)
{
/**
* Remove cache
*/
if(is_array($event->cache_keys)){
foreach($event->cache_keys as $index => $cache_key){
\Cache::forget($cache_key);
Log::debug("[CACHE] Deleted cache for: " . $cache_key);
}
} else {
\Cache::forget($event->cache_keys);
Log::debug("[CACHE] Deleted cache for: " . $event->cache_keys);
}
/**
* Rebuild cache for BrandCampaigns
*/
$campaigns = BrandCampaign::with(['influencers' => function($query){
$query->with(['influencer' => function($query){
$query->select('id','profile_picture');
}])->latest();
}])->where('user_id', $event->user_id )->latest()->get();
$total_influencers = [];
foreach($campaigns as $campaign){
foreach ($campaign->influencers as $influencer) {
if(!in_array($influencer->influencer_id, $total_influencers))
$total_influencers[] = $influencer->influencer_id;
}
}
$total_influencers = count($total_influencers);
$campaigns = collect($campaigns)->toArray();
\Cache::forever('@suppliers_campaigns('.$event->user_id.')', $campaigns);
\Cache::put('@suppliers_total_campaigns('.$event->user_id.')', $total_influencers, 10);
Log::debug("[CACHE] Cache rebuilt successfully!");
return $event;
}
}
I want to cache an array "forever"
, but in my campaign controller, after the event is fired, when I pull the array from cache it is returning null
Thanks!
'@suppliers_campaigns('.$event->user_id.')'
和值$campaigns
不为空且正确吗?suppliers_total_campaigns
缓存是否正常工作? - Mtxzuse Illuminate\Support\Facades\Cache;
?也许你正在使用指向不同配置的不同缓存类。 - Adrian Hernandez-LopezEventServiceProvider.php
文件中注册了事件和监听器的组合? - Taha Paksu