Laravel中无法实例化Spatie\Health\ResultStores\ResultStore接口的问题
问题
在Laravel项目中使用ResultStore时,实例化触发错误:Cannot instantiate interface Spatie\Health\ResultStores\ResultStore,相关代码如下:
获取健康状态的代码
/** * Get health status */ public function getHealthStatus(): array { $schema = [ 'label' => 'Healthy', 'state' => 'healthy', 'textClass' => 'white', 'bgClass' => 'success' ]; try { $latestResults = (new ResultStore())->latestResults(); // health checks not found if (! $latestResults) { $schema['label'] = 'Progressing'; $schema['state'] = 'progressing'; $schema['textClass'] = 'white'; $schema['bgClass'] = 'info'; return $schema; } $failedChecks = collect($latestResults->storedCheckResults)->filter(function ($item) { return $item->status == 'failed'; })->count(); $warnChecks = collect($latestResults->storedCheckResults)->filter(function ($item) { return $item->status == 'warning'; })->count(); if ($warnChecks > 0) { $schema['label'] = 'Degraded'; $schema['state'] = 'degraded'; $schema['textClass'] = 'dark'; $schema['bgClass'] = 'warning'; } if ($failedChecks > 0) { $schema['label'] = 'Critical'; $schema['state'] = 'critical'; $schema['textClass'] = 'white'; $schema['bgClass'] = 'danger'; } } catch (Exception $e) { // ... } return $schema; }
调用该方法的代码
/** * Get app content */ public function app(): array { $stats = []; $stats['health_status'] = $this->getHealthStatus(); return $stats; }
解答
错误根源
Spatie\Health\ResultStores\ResultStore是接口,接口不能直接实例化,必须使用它的具体实现类。
解决办法
你有三种可行的方式获取可用的ResultStore实例:
1. 依赖注入
修改类的构造函数,注入ResultStore接口,Laravel会自动根据配置解析为对应的实现类:
use Spatie\Health\ResultStores\ResultStore; class YourClass { protected $resultStore; public function __construct(ResultStore $resultStore) { $this->resultStore = $resultStore; } public function getHealthStatus(): array { // ... $latestResults = $this->resultStore->latestResults(); // ... } }
2. 容器直接解析
如果无法使用构造注入,直接从Laravel容器中获取实例:
// 在getHealthStatus方法内替换原实例化代码 $latestResults = app(ResultStore::class)->latestResults();
3. 使用门面(如果提供)
若Spatie Health有对应的门面类,可以直接调用:
// 示例:假设门面为HealthResultStore $latestResults = HealthResultStore::latestResults();
补充说明
Spatie Health默认的ResultStore实现是Spatie\Health\ResultStores\DatabaseResultStore,你可以在config/health.php的result_stores配置项中查看或修改默认使用的存储实现。
内容的提问来源于stack exchange,提问作者Ryan H
相关产品推荐
相关产品推荐

