Sushi进阶用法:使用getRows()方法实现动态数据源集成

张开发
2026/4/9 18:51:42 15 分钟阅读

分享文章

Sushi进阶用法:使用getRows()方法实现动态数据源集成
Sushi进阶用法使用getRows()方法实现动态数据源集成【免费下载链接】sushiEloquents missing array driver.项目地址: https://gitcode.com/gh_mirrors/su/sushiSushi是Eloquent缺失的array驱动它允许开发者在不依赖传统数据库的情况下使用Eloquent模型。本文将详细介绍如何通过getRows()方法实现动态数据源集成让你的Laravel应用更灵活地处理各类数据。为什么选择getRows()方法默认情况下Sushi通过protected $rows属性提供静态数据。但在实际开发中我们经常需要从外部API、CSV文件或其他动态源获取数据。这时getRows()方法就成为了连接动态数据源与Eloquent模型的桥梁。getRows()方法的核心优势动态数据处理支持从任意数据源实时获取数据灵活集成轻松对接外部API、文件系统或其他服务按需加载只在需要时获取数据优化性能代码解耦将数据获取逻辑封装在模型内部基础实现自定义getRows()方法实现getRows()方法非常简单只需在Sushi模型中定义该方法并返回数组格式的数据即可。class Role extends Model { use \Sushi\Sushi; public function getRows() { return [ [id 1, label admin], [id 2, label manager], [id 3, label user], ]; } }这个基础示例展示了如何手动返回数据数组。与直接使用$rows属性相比getRows()方法让你可以在返回数据前进行各种处理和转换。高级应用从外部API获取数据getRows()方法的真正强大之处在于能够集成外部数据源。以下示例展示了如何从外部API获取数据并转换为Sushi可用的格式class Currency extends Model { use \Sushi\Sushi; protected $schema [ code string, name string, rate float, ]; public function getRows() { $response Http::get(https://api.exchangerate-api.com/v4/latest/USD); $rates $response-json()[rates]; return collect($rates)-map(function ($rate, $code) { return [ code $code, name Str::upper($code), rate $rate, ]; })-values()-all(); } }缓存策略提升动态数据源性能默认情况下使用自定义getRows()方法时Sushi不会缓存数据。对于频繁访问的数据源这可能导致性能问题。我们可以通过重写sushiShouldCache()方法来启用缓存class Product extends Model { use \Sushi\Sushi; public function getRows() { return CSV::fromFile(storage_path(data/products.csv))-toArray(); } protected function sushiShouldCache() { return true; } protected function sushiCacheReferencePath() { return storage_path(data/products.csv); } }这个配置告诉Sushi启用缓存功能当products.csv文件修改时才更新缓存处理空数据集定义安全的模型架构当getRows()可能返回空数组时Sushi需要明确的架构定义来创建数据库表。通过$schema属性可以定义表结构class WeatherData extends Model { use \Sushi\Sushi; protected $schema [ date date, temperature float, humidity float, precipitation float, ]; public function getRows() { // 可能返回空数组的API调用 $response Http::get(https://api.weather.com/historical-data); return $response-json() ?? []; } }最佳实践与注意事项数据类型处理Sushi会根据返回数据自动推断字段类型但对于复杂场景建议通过$schema属性明确指定protected $schema [ price decimal:8,2, stock integer, available boolean, release_date date, ];性能优化对于大型数据集实现分页逻辑对频繁访问的数据启用缓存考虑使用队列处理耗时的数据获取操作错误处理在getRows()方法中添加适当的错误处理确保模型在数据源不可用时仍能正常工作public function getRows() { try { $response Http::timeout(5)-get(https://api.example.com/data); $response-throw(); return $response-json(); } catch (Exception $e) { // 记录错误 Log::error(Failed to fetch data: . $e-getMessage()); // 返回默认数据或空数组 return []; } }总结getRows()方法为Sushi模型提供了强大的动态数据源集成能力使你能够轻松连接各种外部数据。通过合理使用缓存策略和架构定义你可以构建高效、灵活且可靠的数据模型。无论是从API获取数据、解析CSV文件还是处理复杂的业务逻辑getRows()都能帮助你在保持Eloquent优雅语法的同时实现数据获取的无限可能。要开始使用Sushi只需通过Composer安装composer require calebporzio/sushi然后创建你的第一个动态数据源模型体验Sushi带来的开发便利【免费下载链接】sushiEloquents missing array driver.项目地址: https://gitcode.com/gh_mirrors/su/sushi创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

更多文章