gpt4 book ai didi

php - Laravel 事件监听器和缓存不起作用

转载 作者:行者123 更新时间:2023-12-03 11:21:56 25 4
gpt4 key购买 nike

我在 Laravel 上开发应用程序时遇到了一些困难。
我想用Event and Listener to delete并重建对象的缓存。

这是代码:

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;
}
}

我想缓存一个数组 "forever" ,但在我的事件 Controller 中,在事件触发后,当我从缓存中拉出数组时,它返回

谢谢!

最佳答案

也适用于 Laravel 5(基于问题)和 Laravel 7(最新)。

use Illuminate\Support\Facades\Cache;

// Remove cache
Cache::forget('brandCampaigns');

// Rebuild cache for BrandCampaigns. Here, when the cache key doesn't exists, the function will be called and the returned value will be stored in the cache
$campaigns = Cache::rememberForever('brandCampaigns', function () {
return BrandCampaign::with(['influencers' => function ($query) {
$query->with(['influencer' => function ($query) {
$query->select('id', 'profile_picture');
}])->latest();
}])->where('user_id', $event->user_id)->latest()->get();
});

关于php - Laravel 事件监听器和缓存不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47309482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com