sansu/save-model

一种新的数据库数据保存方式

dev-main 2021-12-31 09:18 UTC

This package is not auto-updated.

Last update: 2024-09-21 20:23:41 UTC


README

Save Model 是一个 Laravel 扩展包,允许您以新的方式在数据库中保存数据。不再需要担心模型中的 $guarded$fillable 属性。只需轻松使用 Save Model 扩展包。

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

安装

您可以通过 composer 安装此包

composer require sansu/save-model

您可以使用以下命令发布配置文件

php artisan save-model:publish

or

php artisan vendor:publish --provider="Asdh\SaveModel\SaveModelServiceProvider"

这是已发布的配置文件的内容

// config/save_model.php

return [
    /**
     * The directory name where the files should be stored
     * This can be changed via 'saveableFields' method on model
     */
    'file_upload_directory' => 'files',
];

使用方法

// In controller

use Asdh\SaveModel\SaveModel;

SaveModel::new(
    new User,
    $request->only(['name', 'email', 'password', 'image'])
)->execute();

// OR

(new SaveModel(
    new User,
    $request->only(['name', 'email', 'password', 'image'])
)->execute();

您只需这样做,就会创建一个新的用户并将其保存到 'users' 表中。密码将被自动哈希,图像上传也将自动处理。

要更新模型,只需传递要更新的模型即可。

// In controller

use Asdh\SaveModel\SaveModel;

$user = User::find(1);

SaveModel::new(
    $user,
    $request->only(['name', 'email'])
)->execute();

只有名称和电子邮件将更新,不会修改其他列。

为了使这生效,您需要做以下事情

前往用户模型类或任何其他模型类,并将 CanBeSavedContract 类添加到其中。在这个例子中,我将使用用户模型。

use Asdh\SaveModel\Contracts\CanBeSavedContract;

class User extends Authenticatable implements CanBeSavedContract
{

}

添加之后,您需要在用户模型中添加 saveableFields 方法,并像这样映射用户表的所有列

use Asdh\SaveModel\Contracts\CanBeSavedContract;
use Asdh\SaveModel\Fields\DatetimeField;
use Asdh\SaveModel\Fields\FileField;
use Asdh\SaveModel\Fields\PasswordField;
use Asdh\SaveModel\Fields\StringField;

class User extends Authenticatable implements CanBeSavedContract
{
    public function saveableFields(): array
    {
        return [
            'name' => StringField::new(),
            'email' => StringField::new(),
            'email_verified_at' => DatetimeField::new(),
            'password' => PasswordField::new(),
            'image' => FileField::new(),
        ];
    }
}

完成这些操作后,您就可以开始了。在控制器中,您只需获取数据并使用 SaveModel 类。

use Asdh\SaveModel\SaveModel;

SaveModel::new(
    new User,
    $request->only(['name', 'email', 'password', 'image'])
)->execute();

// OR

(new SaveModel(
    new User,
    $request->only(['name', 'email', 'password', 'image'])
)->execute();

文件将使用默认的 Laravel 文件系统 上传。这意味着您可以直接配置将文件直接上传到 S3 或任何 Laravel 支持的其他服务。

此外,文件默认将上传到 files 目录。您可以通过更改 save_model.php 配置文件中的 file_upload_directory 值全局更改此设置。

您也可以按模型更改它

// app/Models/User.php

public function saveableFields(): array
{
    return [
        'image' => FileField::new()->setDirectory('images'),
    ];
}

现在它将用户的 image 保存到 images 目录,而对于其他 模型,它将使用 save_model.php 配置文件。

您也可以为每个模型选择 Laravel 文件系统的 disk

// app/Models/User.php

public function saveableFields(): array
{
    return [
        'image' => FileField::new()
            ->setDirectory('images')
            ->setDisk('s3'),
    ];
}

默认情况下,上传的文件将生成随机名称,但您也可以更改它。您只需在 setFileName 方法中传递闭包即可。您将可以访问上传的文件,并在这里返回的内容将被保存到数据库中作为文件名。

此示例展示了如何返回原始文件名。

// app/Models/User.php

use Illuminate\Http\UploadedFile;

public function saveableFields(): array
{
    return [
        'image' => FileField::new()
            ->setDirectory('images')
            ->setFileName(function (UploadedFile $uploadedFile) {
                return $uploadedFile->getClientOriginalName();
            }),
    ];
}

如果您想以原始名称上传文件,可以这样做

// app/Models/User.php

use Illuminate\Http\UploadedFile;

public function saveableFields(): array
{
    return [
        'image' => FileField::new()
            ->setDirectory('images')
            ->uploadAsOriginalName(),
    ];
}

请注意,如果同时使用 setFileNameuploadAsOriginalName 方法,则 setFileName 方法将具有优先级。

不仅如此,更新模型时文件删除也将自动处理。默认情况下,如果上传了新文件,则模型更新时旧文件将被自动删除。如果您不想删除旧图像,则可以链式调用 dontDeleteOldFileOnUpdate 方法。

// app/Models/User.php

use Illuminate\Http\UploadedFile;

public function saveableFields(): array
{
    return [
        'image' => FileField::new()
            ->setDirectory('images')
            ->dontDeleteOldFileOnUpdate(),
    ];
}

可用字段

Asdh\SaveModel\Fields\StringField::class
Asdh\SaveModel\Fields\IntegerField::class
Asdh\SaveModel\Fields\DatetimeField::class
Asdh\SaveModel\Fields\DateField::class
Asdh\SaveModel\Fields\TimeField::class
Asdh\SaveModel\Fields\PasswordField::class
Asdh\SaveModel\Fields\FileField::class
Asdh\SaveModel\Fields\BooleanField::class

将来将添加其他字段,我欢迎 pull requests。

创建自己的模型字段类

您也可以创建自己的字段类。要创建一个,您需要运行 artisan 命令

php artisan make:field BooleanField

这将创建一个位于 App\ModelFields 目录中的 BooleanField 类,它看起来像这样

<?php

namespace App\ModelFields;

use Asdh\SaveModel\Fields\Field;

class BooleanField extends Field
{
    public function execute(): mixed
    {
        // Perform your logic and return the value...

        // return strtoupper($this->value)
    }
}

并不一定要求 BooleanField 类位于 App\ModelFields 目录中。您可以将它放在任何您喜欢的位置。

您将能够访问从控制器传递过来的数据,通过$this->value。然后您可以进行任何操作,并返回您想要保存到数据库中的值。在上面的例子中,我们可以这样做:

<?php

namespace App\ModelFields;

use Asdh\SaveModel\Fields\Field;

class BooleanField extends Field
{
    public function execute(): mixed
    {
        return in_array($this->value, [1, '1', true, 'true', 'on', 'yes']);
    }
}

如果输入是以下任何一个,我们将将其视为真,并为这些值中的每一个都保存true(在数据库中存储时为1)。

然后您可以在模型的saveableFields方法中轻松使用自己的字段。现在,您可以像这样使用这个BooleanField和其他字段:

use Asdh\SaveModel\Contracts\CanBeSavedContract;
use Asdh\SaveModel\Fields\DatetimeField;
use Asdh\SaveModel\Fields\FileField;
use Asdh\SaveModel\Fields\PasswordField;
use Asdh\SaveModel\Fields\StringField;
use App\ModelFields\BooleanField;

class User extends Authenticatable implements CanBeSavedContract
{
    public function saveableFields(): array
    {
        return [
            'name' => StringField::new(),
            'email' => StringField::new(),
            'email_verified_at' => DatetimeField::new(),
            'password' => PasswordField::new(),
            'image' => FileField::new(),
            'is_admin' => Boolean::new(),
        ];
    }
}

确保正确添加命名空间,如上所示。

测试

composer test

变更日志

有关最近更改的更多信息,请参阅变更日志

贡献

有关详细信息,请参阅贡献指南

许可证

MIT许可证(MIT)。有关更多信息,请参阅许可证文件