Laravel Sushi - Eloquent的数组驱动程序
Laravel  /  管理员 发布于 1年前   334
什么是 Laravel Sushi?
Laravel Sushi是Caleb Porzio的软件包,根据软件包的README,Sushi 是 "Eloquent 缺失的'数组'驱动"。
换句话说,它允许你从数据库以外的数据源创建 Eloquent 模型。
使用它的最简单方法是在模型文件中设置 $rows 属性,将数据作为硬编码数组提供。
其他时候,您可以使用 getRows 提供动态数据--来自 API 源、CSV 文件或您选择的其他任何地方。
那么它究竟是如何工作的呢?
Sushi接收您提供的数据,创建 Eloquent 模型,然后将其缓存到 sqlite 数据库中。
然后,你就可以像查询任何标准 Eloquent 模型一样查询数据了。
下面是一个Sushi模型的基本示例:
<?php
namespace App\Models;
use Sushi\Sushi;
class Role extends Model
{
// Add the trait
use Sushi;
// Provide the data as a hardcoded array
protected $rows = [
['id' => 1, 'label' => 'admin'],
['id' => 2, 'label' => 'manager'],
['id' => 3, 'label' => 'user'],
];
}
Laravel Sushi状态
让我们来看看我和其他人用过的一些实际例子。最基本的例子是创建状态列表或表格。
Ken 和 Facundo 提到过这个用例,我个人也用过。
<?php
namespace App\Models;
use Sushi\Sushi;
class Role extends Model
{
use Sushi;
protected $rows = [
[
'id' => 1,
'name' => 'Alabama',
'abbreviation' => 'AL',
],
[
'id' => 2,
'name' => 'Alaska',
'abbreviation' => 'AK',
],
[
'id' => 3,
'name' => 'Arizona',
'abbreviation' => 'AZ',
],
[
'id' => 4,
'name' => 'Arkansas',
'abbreviation' => 'AR',
],
[
'id' => 5,
'name' => 'California',
'abbreviation' => 'CA',
],
// ...
];
}
注意:
"id "列是可选的。
Sushi 可以为每个条目创建自动递增的 ID,
但如果条目发生变化(缓存被破坏),就不能保证条目会收到与之前相同的 ID。
如果要将其他数据与 Sushi 模型关联,最好为每个项目提供一个静态 ID 列。
用于博客、课程和信息产品的 Laravel Sushi
另一个方便的用例是简单的博客和课程。
有时,作为一名开发人员,我需要为博客或课程存储一些页面,但我并不需要一个完整的内容管理系统。我宁愿保持轻量级,同时将所有内容直接存储在代码中,这样就可以通过 Git 同步。
亚伦提到他在 aaronfrancis.com 上的博客就是使用这种设置。
Caleb 提到 Livewire v2 截屏平台也使用了类似的设置:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Sushi\Sushi;
class Series extends Model
{
use Sushi;
public function screencasts()
{
return $this->hasMany(Screencast::class);
}
public function getRows()
{
return [
['id' => 1, 'order' => 1, 'title' => 'Getting Started'],
['id' => 2, 'order' => 2, 'title' => 'A Basic Form With Validation'],
//...
];
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Sushi\Sushi;
class Screencast extends Model
{
use Sushi;
public function series()
{
return $this->belongsTo(Series::class);
}
public function getNextAttribute()
{
return static::find($this->id + 1);
}
public function getPrevAttribute()
{
return static::find($this->id - 1);
}
public function getDurationInSecondsAttribute()
{
// ...
}
protected $rows = [
[
'title' => 'Installation',
'slug' => 'installation',
'description' => "Installing Livewire is so simple, this 2.5 minute video feels like overkill. Composer require, and two little lines added to your layout file, and you are fully set up and ready to rumble!",
'video_url' => 'https://vimeo.com/...',
'code_url' => 'https://github.com/...',
'duration_in_minutes' => '2:32',
'series_id' => 1,
],
[
'title' => 'Data Binding',
'slug' => 'data-binding',
'description' => "The first and most important concept to understand when using Livewire is "data binding". It's the backbone of page reactivity in Livewire, and it'll be your first introduction into how Livewire works under the hood. Mandatory viewing.",
'video_url' => 'https://vimeo.com/...',,
'code_url' => 'https://github.com/...',
'duration_in_minutes' => '9:11',
'series_id' => 1,
],
// ...
];
}
正如你在本例中看到的,由于这些是真正的 Eloquent 模型,你可以像在普通模型上一样添加关系、获取器和辅助方法。
有了这些模型,你就可以在控制器或 Livewire 组件中查询它们,就像查询数据库驱动的模型一样:
$series = Series::with(['screencasts'])->orderBy('order')->get();
然后,您就可以在Blade模板中循环播放:
<div>
@foreach($series as $s)
<div>
<h2>{{ $series->title }}</h2>
<div>
@foreach($series->screencasts as $screencast)
<div>
<h3>{{ $screencast->title }}</h3>
<p>{{ $screencast->description }}</p>
</div>
@endforeach
</div>
</div>
@endforeach
</div>
你甚至可以使用 Laravel 的路由模型绑定来自动查询 Sushi 模型:
Route::get('/screencasts/{screencast:slug}');
Caleb 和我使用非常相似的方法来存储高山组件的组件。
我们使用路由模型绑定路由,然后使用 Blade 视图显示每个组件的详细信息。
在 Blade 视图中,我们循环查看组件的变体,并使用 @include($variant->view) 包括单独的硬编码 Blade 视图,这些视图包含组件的实际代码。
<?php
namespace App\Models;
use App\Enums\ComponentType;
use Illuminate\Database\Eloquent\Model;
use Sushi\Sushi;
class Component extends Model
{
use Sushi;
protected $casts = [
'variants' => 'collection',
'requirements' => 'collection',
'type' => ComponentType::class,
];
public function getRows()
{
return [
[
'title' => 'Dropdown',
'slug' => 'dropdown',
'description' => 'How to build a dropdown component using Alpine.js.',
'screencast_id' => 111,
'variants' => json_encode([
['view' => 'patterns.dropdown'],
]),
'type' => ComponentType::COMPONENT->value,
'is_public' => true,
'is_free' => true,
'requirements' => json_encode([
[
'name' => 'alpinejs',
'version' => 'v3.x',
'url' => 'https://alpinejs.dev/installation',
],
]),
],
[
'title' => 'Modal',
'slug' => 'modal',
'description' => 'How to build a modal component using Alpine.js.',
'screencast_id' => 222,
'variants' => json_encode([
['view' => 'patterns.modal'],
]),
'type' => ComponentType::COMPONENT->value,
'is_public' => true,
'is_free' => false,
'requirements' => json_encode([
[
'name' => 'alpinejs',
'version' => 'v3.x',
'url' => 'https://alpinejs.dev/installation',
],
[
'name' => '@alpinejs/focus',
'version' => 'v3.x',
'url' => 'https://alpinejs.dev/plugins/focus',
],
]),
],
// ...
];
}
}
正如您在本例中看到的,我们使用了 getRows 方法,而不是设置 $rows 属性。
这样我们就可以使用 json_encode()函数,并为每个模型上的变体和需求列使用 JSON 列。
你还可以看到 Sushi 和 Laravel 一样,支持将属性转换为不同的类型。
API 数据源
另一个出色的用例是从 API 源获取数据。
Raúl、Marcel、Adam 和 Caleb 提到了他们使用过的不同 API 源。
Caleb 向 GitHub Sponsors API 发送请求,以确定谁可以访问 Livewire v2 截屏,然后映射这些结果以获取所需的属性,并将其格式化为一个漂亮的模型模式。
这是 Livewire v2 代码库中赞助商模型的简化版本:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Sushi\Sushi;
class Sponsor extends Model
{
use Sushi;
protected $keyType = 'string';
public function user()
{
return $this->hasOne(User::class, 'github_username', 'username');
}
public function getsScreencasts()
{
// If they sponsor for more than $8, they get access to screencasts.
return $this->tier_price_in_cents > 8 * 100;
}
public function getRows()
{
return Cache::remember('sponsors', now()->addHour(), function () {
return collect($this->fetchSponsors())
->map(function ($sponsor) {
return [
'id' => $sponsor['sponsorEntity']['id'],
'username' => $sponsor['sponsorEntity']['login'],
'name' => $sponsor['sponsorEntity']['name'],
'email' => $sponsor['sponsorEntity']['email'],
// ...
];
});
});
}
public function fetchSponsors()
{
return Http::retry(3, 100)
->withToken(
config('services.github.token')
)->post('https://api.github.com/graphql', [
'query' => 'A big ugly GraphQL query'
]);
}
}
总结
Sushi 是一个非常出色的软件包,它有一些非常棒的用例,我相信我在这篇文章中仅仅触及了皮毛。
相关链接:
https://github.com/calebporzio/sushi
https://laravel-news.com/laravel-sushi
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号