wefabric/form-cache

Laravel 包,用于缓存表单数据一段时间

dev-main 2021-12-30 09:57 UTC

This package is auto-updated.

Last update: 2024-08-29 05:50:35 UTC


README

Laravel 包,用于缓存表单数据一段时间。

安装

此包可以通过 Composer 安装。

composer require wefabric/form-cache

使用以下命令发布配置和迁移文件

php artisan vendor:publish --tag="wefabric_form_cache"

迁移数据库

php artisan migrate

将表单缓存垃圾回收器命令添加到 App\Console\Kernel。它将在默认作业连接上执行。添加参数 '--now' 以立即运行。

// Form cache
$schedule->command('form-cache:garbage-collection')->everyFiveMinutes();

使用方法

在此示例中,我们将使用 Livewire 组件将表单数据保存到数据库缓存中。

在构造函数(或 Livewire 的挂载方法)中,我们调用带有表单缓存键属性的 'fillFromFormCache'。它会自动用保存的数据填充所有公共属性。

保存表单时,您可以使用带有表单缓存键属性的 'saveToFormCache' 方法。这将检索类中所有公共属性并将其保存到数据库中。

要排除属性,可以将属性名添加到受保护的属性 'excludeFromFormCache' 中。

示例代码

use Livewire\Component;
use Wefabric\FormCache\Concerns\UsesFormCaches;

class MyForm extends Component
{
    use UsesFormCaches;

    protected string $formCacheKey = 'my-form';

    public array $formData = [
        'first_name' => '',
        'last_name' => ''
    ];
    
    /**
     * Exclude properties from the form cache
     * @var array
     */
    protected array $excludeFromFormCache = [

    ];
    
    public function mount()
    {
        $this->formHash = $formHash;

        $this->fillFromFormCache();
    } 
    
    public function saveFormData()
    {
        $this->saveToFormCache();
    }
    
    public function send()
    {
        // Your send logic
        $this->deleteFormData();
    }
}

要设置缓存过期日期,编辑表单缓存的 'expires_after' 配置。