mortenscheel/laravel-automation

Laravel 自动化框架

v0.1 2022-03-20 19:57 UTC

README

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

允许用户在 Laravel 应用中配置动态自动化流程。受 If this then that 启发,您定义一系列触发器和动作,然后允许用户将它们组合并配置。

快速开始

使用 composer 安装包

composer require mortenscheel/laravel-automation

发布并运行迁移

php artisan vendor:publish --tag="automation-migrations"
php artisan migrate

通过 Laravel 的调度器在 app/Console/Kernel.php 中自动运行自动化任务

protected function schedule(Schedule $schedule)
{
    // ...
    $schedule->command('automation:run');
}

概念

AutomationTrigger

自定义类,负责发现满足其标准的模型。

AutomationAction

自定义作业类,对模型执行操作。

Automation 模型

一个具体的自动化工作流程,结合了一个 AutomationTrigger 和一个 AutomationAction。还包括(可选)触发器和动作的参数。

AutomationLog 模型

当对特定模型执行 Automation 时创建的记录。

Automatable 接口

为了使模型可自动化,它们必须实现 Automatable 接口。

示例

新用户创建后 15 分钟发送欢迎邮件

Automation 模型可能看起来像这样

Automation::create([
    'trigger_class' => ModelAgeTrigger::class,
    'trigger_params' => [
        'model' => User::class,
        'age' => 60 * 15,
    ],
    'action_class' => SendMailableAction::class,
    'action_params' => [
        'mailable' => WelcomeEmail::class,
        'mailable_params' => [
            'name',
        ],
    ],
]);

触发器类只需要实现一个方法

class ModelAgeTrigger extends \Scheel\Automation\AutomationTrigger
{
    public function discoverAutomatable(Automation $automation): Collection
    {
        $class = $this->params->get('model');
        return $class::query()->where('created_at', '<=', now()->subSeconds($this->params->get('age')))
            ->whereDoesntHave('automationLogs', fn ($logs) => $logs->where('automation_id', $automation->id))
            ->get();
    }
}

动作类也很简单

class SendMailableAction extends \Scheel\Automation\AutomationAction
{
    protected function executeAction(): bool
    {
        $params = $this->log->automation->action_params;
        $mailable_class = $params->get('mailable');
        $recipient = $this->log->automatable;
        $mailable_params = [];
        foreach ($params->get('mailable_params', []) as $mailable_param) {
            $mailable_params[] = data_get($recipient, $mailable_param);
        }
        $mailable = new $mailable_class(...$mailable_params);
        \Mail::to($recipient)->send($mailable);
        return true;
    }
}

待办事项

此包仍在开发中,欢迎反馈或拉取请求。以下是我希望改进的一些区域:

  • 添加更多示例触发器和动作(带测试)。
  • 允许使用自定义的 Automation 子类(wip)。
  • 添加更多文档。

测试

composer test

变更日志

请参阅 CHANGELOG 了解最近更改的更多信息。

贡献

请参阅 CONTRIBUTING 了解详情。

安全漏洞

请参阅 我们的安全策略 了解如何报告安全漏洞。

致谢

许可证

MIT 许可证(MIT)。请参阅 许可证文件 了解更多信息。