adelaide/laravel-fluent

基于based/laravel-fluent的分支。使用流畅的方式定义模型属性。自动将属性转换为原生类型。

资助包维护!
lepikhinb

v1.0.0 2022-11-04 22:12 UTC

This package is auto-updated.

Last update: 2024-09-05 02:09:47 UTC


README

该包提供了一种表达性的"流畅"方式来定义模型属性。它将在运行时自动构建类型转换,并为模型的属性添加原生自动完成。

简介

使用 laravel-fluent,你可以像定义其他任何类的属性一样定义模型属性。值将根据属性的本地类型转换为相应的类型。

之前

<?php

/**
 * @property Collection $features
 * @property float $price
 * @property int $available
 */
class Product extends Model
{
    protected $casts = [
        'features' => 'collection',
        'price' => 'float',
        'available' => 'integer',
    ];
}

之后

<?php

class Product extends Model
{
    use HasFluentBindings;

    public Collection $features;
    public float $price;
    public int $available;
}

安装

此版本支持PHP 8.0。您可以通过composer安装该包

composer require based/laravel-fluent

然后,将Based\Fluent\Fluent特质添加到您的模型中

<?php

class User extends Model
{
    use HasFluentBindings;
}

模型属性

定义公共属性。laravel-fluent支持所有原生类型和Laravel基本转换

<?php

class Order extends Model
{
    use HasFluentBindings;

    public int $amount;
    public Carbon $expires_at;

    #[AsDecimal(2)]
    public float $total;

    #[Cast('encrypted:array')]
    public array $payload;
}

可填充和受保护

任何由库管理的属性都可以通过标注属性来标记为可填充或受保护。

<?php

class Order extends Model
{
    use HasFluentBindings;

    #[Guarded]
    public int $id;

    #[Fillable]
    public int $amount;

    #[Fillable]
    #[AsDecimal(2)]
    public float $total;

    #[Cast('encrypted:array')]
    public array $payload;
}

这些属性也可以在类级别指定,并将影响多个属性。

<?php

/*
 * All properties will be marked as fillable.
 * See Fillable's documentation for more nuanced controls.
 */
#[Fillable(Fillable::INCLUDE_ALL)]
class Order extends Model
{

    use HasFluentBindings;

    public int $id;
    public int $amount;

    #[AsDecimal(2)]
    public float $total;
}

关系

该包还处理关系。

<?php

class Product extends Model
{
    use HasFluentBindings;

    #[Relation]
    public Collection $features;
    public Category $category;

    public function features(): HasMany
    {
        return $this->hasMany(Feature::class);
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }
}

该包可以自动从属性中解析关系,但请注意,将没有相关Laravel样式的方法的自动完成。

<?php

class Product extends Model
{
    use HasFluentBindings;

    #[HasMany(Feature::class)]
    public Collection $features;
    #[BelongsTo]
    public Category $category;

    /*
     * The Laravel-style methods `features()` and `category()` will
     * be simulated under the hood, but will lack IDE autocompletion.
     */
}

测试

composer test

待办事项

  • 迁移生成器

致谢

许可

MIT许可(MIT)。请参阅许可文件获取更多信息。