侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Laravel Sushi - Eloquent的数组驱动程序

Laravel  /  管理员 发布于 1个月前   63

什么是 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

  • 上一条:
    Laravel 10.17版本发布
    下一条:
    Laravel Livewire Volt拥有基于类的新API
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel 10.24版本发布(0个评论)
    • Laravel应用程序性能监控 (APM) 工具:Scout (0个评论)
    • laravel框架中以公共函数方式实现job异步化执行封装代码示例(0个评论)
    • Laravel HTTP 测试与Symfony的DomCrawler(0个评论)
    • 使用 Laravel Rest Api 轻松生成 Apis(0个评论)
    • 近期文章
    • Laravel 10.24版本发布(0个评论)
    • go语言多项目批量更新依赖及自动调用jenkins构建流程步骤(0个评论)
    • 在go语言中实现数学pow(x^y 的幂次)代码示例(0个评论)
    • Laravel应用程序性能监控 (APM) 工具:Scout (0个评论)
    • 推荐一款针对git、diff和grep输出的语法高亮显示的扩展包:Git Delta(0个评论)
    • laravel框架中以公共函数方式实现job异步化执行封装代码示例(0个评论)
    • 在go语言中实现从http响应中解码JSON数据(0个评论)
    • go语言中如何使用JSON网络令牌(JWT)在控制器之间传递数据(0个评论)
    • 计算机网络知识详解(0个评论)
    • Laravel HTTP 测试与Symfony的DomCrawler(0个评论)
    • 近期评论
    • 路人 在

      php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例中评论 教程很详细,如果加个前端chatgpt对话页面就完美了..
    • 博主 在

      科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 @ mashrdn 多切换几个节点测试,免费ssr是没那么稳..
    • mashrdn 在

      科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 V2rayn免费节点添加上去了,youtobe无法打开网页,是怎么回事..
    • 张伟 在

      科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 3q!有用,不过免费节点隔天就要去git上复制新的导进去..
    • 博主 在

      科学上网翻墙访问Google , 上外网神器佛跳墙VPN(永久免费)使用流程步骤中评论 该篇教程已不能用了,告知大家,免的老有老铁问我!..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-01
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客