star-cloud/app/Console/Commands/WarmProductsCacheCommand.php
sky121113 2c8a2de81c [FEAT] 實作商品主檔 B012 Redis 快取機制 (Phase 1)
1. 新增 ProductCatalogService 負責商品清單轉換與 Redis 快取邏輯。
2. 新增 WarmProductsCacheCommand (artisan products:warm-cache) 用於預熱快取。
3. 修改 ProductController 在商品異動時自動重建快取。
4. 修改 MachineController@getProducts (B012) 改為 Cache-First 讀取。
5. 在 Company 模型補上 products 關聯以支援暖機指令。
2026-05-13 18:51:35 +08:00

63 lines
1.7 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\System\Company;
use App\Services\Product\ProductCatalogService;
use Illuminate\Console\Command;
class WarmProductsCacheCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'products:warm-cache {--company= : ID of the specific company to warm cache for}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Pre-warm the Redis cache for product catalogs of all or a specific company.';
/**
* Execute the console command.
*
* @param ProductCatalogService $catalogService
* @return int
*/
public function handle(ProductCatalogService $catalogService): int
{
$companyId = $this->option('company');
if ($companyId) {
$companies = Company::where('id', $companyId)->pluck('id');
} else {
// Only warm companies that actually have products to avoid empty cache entries
$companies = Company::whereHas('products')->pluck('id');
}
if ($companies->isEmpty()) {
$this->warn('No companies found with products to warm cache for.');
return self::SUCCESS;
}
$this->info("Starting to warm product catalog cache for {$companies->count()} companies...");
$bar = $this->output->createProgressBar($companies->count());
$bar->start();
foreach ($companies as $id) {
$catalogService->rebuildCache($id);
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info('✅ Product catalog cache warming completed!');
return self::SUCCESS;
}
}