solution-forest/workflow-engine-laravel 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

solution-forest/workflow-engine-laravel

Composer 安装命令:

composer require solution-forest/workflow-engine-laravel

包简介

Laravel integration for the Workflow Engine - providing Eloquent models, service providers, and artisan commands for seamless workflow management

README 文档

README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

A modern, type-safe workflow engine for Laravel built with PHP 8.3+ features

Create powerful business workflows with simple, maintainable code.

⚠️ WARNING: DEVELOPMENT STATUS⚠️

This package is currently under active development and is NOT READY FOR PRODUCTION USE.

Features may be incomplete, APIs might change, and there could be breaking changes. Use at your own risk in development environments only.

✨ Why Choose This Workflow Engine?

  • 🎨 Simple & Intuitive - Array-based workflow definitions and fluent WorkflowBuilder API
  • 🏷️ Modern PHP 8.3+ Attributes - Declarative configuration with #[WorkflowStep], #[Retry], #[Timeout]
  • 🔒 Type Safety First - Built with enums, strong typing, and modern PHP features
  • Laravel Native - Seamless integration with Laravel's ecosystem and helpers
  • 🧩 Extensible - Easy to extend with custom actions and storage adapters
  • 📚 Well Tested - Comprehensive test suite with real-world examples

🚀 Quick Start

Installation

composer require solution-forest/workflow-engine-laravel

Optionally publish the config file:

php artisan vendor:publish --tag="workflow-engine-config"

For database storage, run the migrations:

php artisan migrate

The migration will create a workflow_instances table to store workflow state and progress.

Your First Workflow in 30 Seconds

use SolutionForest\WorkflowEngine\Core\WorkflowEngine;

// Create a simple workflow definition
$definition = [
    'name' => 'User Onboarding',
    'version' => '1.0',
    'steps' => [
        [
            'id' => 'welcome',
            'name' => 'Send Welcome',
            'action' => 'log',
            'parameters' => [
                'message' => 'Welcome {{ user.name }}!',
                'level' => 'info'
            ]
        ],
        [
            'id' => 'setup',
            'name' => 'Setup Account', 
            'action' => 'log',
            'parameters' => [
                'message' => 'Setting up account for {{ user.email }}',
                'level' => 'info'
            ]
        ]
    ]
];

// Start the workflow using the engine
$workflowId = workflow()->start('user-onboarding-001', $definition, [
    'user' => ['name' => 'John Doe', 'email' => 'john@example.com']
]);

// Or use the helper functions
$workflowId = start_workflow('user-onboarding-002', $definition, [
    'user' => ['name' => 'Jane Doe', 'email' => 'jane@example.com']
]);

💼 Real-World Examples

E-commerce Order Processing

$definition = [
    'name' => 'Order Processing',
    'version' => '1.0',
    'steps' => [
        [
            'id' => 'validate-order',
            'name' => 'Validate Order',
            'action' => 'log',
            'parameters' => [
                'message' => 'Validating order {{ order.id }}',
                'level' => 'info'
            ]
        ],
        [
            'id' => 'process-payment',
            'name' => 'Process Payment',
            'action' => 'log',
            'parameters' => [
                'message' => 'Processing payment for {{ order.total }}',
                'level' => 'info'
            ]
        ],
        [
            'id' => 'fulfill-order',
            'name' => 'Fulfill Order',
            'action' => 'log',
            'parameters' => [
                'message' => 'Order {{ order.id }} fulfilled',
                'level' => 'info'
            ]
        ]
    ]
];

$workflowId = start_workflow('order-001', $definition, [
    'order' => ['id' => 'ORD-001', 'total' => 99.99]
]);

Document Approval Process

$definition = [
    'name' => 'Document Approval',
    'version' => '1.0',
    'steps' => [
        [
            'id' => 'submit',
            'name' => 'Submit Document',
            'action' => 'log',
            'parameters' => [
                'message' => 'Document {{ document.id }} submitted by {{ user.name }}',
                'level' => 'info'
            ]
        ],
        [
            'id' => 'review',
            'name' => 'Manager Review',
            'action' => 'log',
            'parameters' => [
                'message' => 'Document {{ document.id }} under review',
                'level' => 'info'
            ]
        ],
        [
            'id' => 'approve',
            'name' => 'Final Approval',
            'action' => 'log',
            'parameters' => [
                'message' => 'Document {{ document.id }} approved',
                'level' => 'info'
            ]
        ]
    ]
];

$workflowId = start_workflow('doc-approval-001', $definition, [
    'document' => ['id' => 'DOC-001'],
    'user' => ['name' => 'John Doe']
]);

User Onboarding

$definition = [
    'name' => 'User Onboarding',
    'version' => '1.0',
    'steps' => [
        [
            'id' => 'welcome',
            'name' => 'Send Welcome Message',
            'action' => 'log',
            'parameters' => [
                'message' => 'Welcome {{ user.name }}! Starting onboarding...',
                'level' => 'info'
            ]
        ],
        [
            'id' => 'setup-profile',
            'name' => 'Setup User Profile',
            'action' => 'log',
            'parameters' => [
                'message' => 'Setting up profile for {{ user.email }}',
                'level' => 'info'
            ]
        ],
        [
            'id' => 'complete',
            'name' => 'Complete Onboarding',
            'action' => 'log',
            'parameters' => [
                'message' => 'Onboarding complete for {{ user.name }}',
                'level' => 'info'
            ]
        ]
    ]
];

$workflowId = start_workflow('onboarding-001', $definition, [
    'user' => ['name' => 'Jane Doe', 'email' => 'jane@example.com']
]);

Creating Custom Actions

<?php

namespace App\Actions;

use SolutionForest\WorkflowEngine\Contracts\WorkflowAction;
use SolutionForest\WorkflowEngine\Core\ActionResult;
use SolutionForest\WorkflowEngine\Core\WorkflowContext;

class SendEmailAction implements WorkflowAction
{
    private array $config;
    
    public function __construct(array $config = [])
    {
        $this->config = $config;
    }
    
    public function execute(WorkflowContext $context): ActionResult
    {
        $to = $this->config['to'] ?? 'default@example.com';
        $subject = $this->config['subject'] ?? 'Notification';
        
        // Process template variables
        $processedTo = $this->processTemplate($to, $context->getData());
        $processedSubject = $this->processTemplate($subject, $context->getData());
        
        // Send email using Laravel's Mail facade
        Mail::to($processedTo)->send(new WorkflowNotification($processedSubject));
        
        return ActionResult::success([
            'email_sent' => true,
            'recipient' => $processedTo
        ]);
    }
    
    private function processTemplate(string $template, array $data): string
    {
        return preg_replace_callback('/\{\{\s*([^}]+)\s*\}\}/', function ($matches) use ($data) {
            $key = trim($matches[1]);
            return data_get($data, $key, $matches[0]);
        }, $template);
    }
}

Then use it in your workflows:

$definition = [
    'name' => 'Email Workflow',
    'steps' => [
        [
            'id' => 'send-email',
            'action' => SendEmailAction::class,
            'parameters' => [
                'to' => '{{ user.email }}',
                'subject' => 'Welcome {{ user.name }}!'
            ]
        ]
    ]
];

🔧 Core Features

Modern PHP 8.3+ Attributes

Enhance your workflow actions with declarative attributes for configuration:

<?php

namespace App\Actions;

use SolutionForest\WorkflowEngine\Attributes\WorkflowStep;
use SolutionForest\WorkflowEngine\Attributes\Timeout;
use SolutionForest\WorkflowEngine\Attributes\Retry;
use SolutionForest\WorkflowEngine\Attributes\Condition;
use SolutionForest\WorkflowEngine\Contracts\WorkflowAction;
use SolutionForest\WorkflowEngine\Core\ActionResult;
use SolutionForest\WorkflowEngine\Core\WorkflowContext;

#[WorkflowStep(
    id: 'send_email',
    name: 'Send Welcome Email',
    description: 'Sends a welcome email to new users'
)]
#[Timeout(minutes: 5)]
#[Retry(attempts: 3, backoff: 'exponential')]
#[Condition('user.email is not null')]
class SendWelcomeEmailAction implements WorkflowAction
{
    public function execute(WorkflowContext $context): ActionResult
    {
        $user = $context->getData('user');
        
        // Send email logic here
        Mail::to($user['email'])->send(new WelcomeEmail($user));
        
        return ActionResult::success(['email_sent' => true]);
    }
}

Available Attributes:

  • #[WorkflowStep] - Define step metadata (id, name, description, config)
  • #[Timeout] - Set execution timeouts (seconds, minutes, hours)
  • #[Retry] - Configure retry behavior (attempts, backoff strategy, delays)
  • #[Condition] - Add conditional execution rules

WorkflowBuilder Fluent API

Create workflows with an intuitive, chainable API:

use SolutionForest\WorkflowEngine\Core\WorkflowBuilder;

$workflow = WorkflowBuilder::create('user-onboarding')
    ->description('Complete user onboarding process')
    ->addStep('welcome', SendWelcomeEmailAction::class)
    ->addStep('setup', SetupUserAction::class, ['template' => 'premium'])
    ->when('user.plan === "premium"', function($builder) {
        $builder->addStep('premium-setup', PremiumSetupAction::class);
    })
    ->email('tips-email', '{{ user.email }}', 'Getting Started Tips')
    ->delay(hours: 24)
    ->addStep('complete', CompleteOnboardingAction::class)
    ->build();

// Start the workflow
$workflowId = $workflow->start('user-001', [
    'user' => ['email' => 'john@example.com', 'plan' => 'premium']
]);

Modern PHP 8.3+ Enums

use SolutionForest\WorkflowEngine\Core\WorkflowState;

// Rich, type-safe workflow states
$state = WorkflowState::RUNNING;
echo $state->color();     // 'blue'
echo $state->icon();      // '▶️'
echo $state->label();     // 'Running'

// Smart state transitions
if ($state->canTransitionTo(WorkflowState::COMPLETED)) {
    workflow()->complete($workflowId);
}

Template Processing

// Use template variables in your workflow steps
$definition = [
    'name' => 'User Notification',
    'steps' => [
        [
            'id' => 'notify',
            'action' => 'log',
            'parameters' => [
                'message' => 'Hello {{ user.name }}, your order {{ order.id }} is ready!',
                'level' => 'info'
            ]
        ]
    ]
];

start_workflow('notification-001', $definition, [
    'user' => ['name' => 'John'],
    'order' => ['id' => 'ORD-123']
]);

Built-in Actions

// Log Action - Built-in logging with template support
[
    'id' => 'log-step',
    'action' => 'log',
    'parameters' => [
        'message' => 'Processing {{ item.name }}',
        'level' => 'info'
    ]
]

// Delay Action - Built-in delays (for testing/demo)
[
    'id' => 'delay-step', 
    'action' => 'delay',
    'parameters' => [
        'seconds' => 2
    ]
]

Workflow Management

// Start workflows
$workflowId = start_workflow('my-workflow', $definition, $context);

// Get workflow status
$instance = get_workflow($workflowId);
echo $instance->getState()->label(); // Current state

// List all workflows
$workflows = list_workflows();

// Filter workflows by state
$runningWorkflows = list_workflows(['state' => WorkflowState::RUNNING]);

// Cancel a workflow
cancel_workflow($workflowId, 'User requested cancellation');

Helper Functions

The package provides convenient helper functions for common operations:

// Get the workflow engine instance
$engine = workflow();

// Start a workflow
$workflowId = start_workflow('my-workflow-id', $definition, $context);

// Get a workflow instance  
$instance = get_workflow('my-workflow-id');

// List all workflows
$workflows = list_workflows();

// List workflows filtered by state
$runningWorkflows = list_workflows(['state' => WorkflowState::RUNNING]);

// Cancel a workflow
cancel_workflow('my-workflow-id', 'User cancelled');

📖 Documentation

🧪 Testing

composer test

📝 Changelog

Please see CHANGELOG for more information on what has changed recently.

🤝 Contributing

Please see CONTRIBUTING for details.

🔒 Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

📄 License

The MIT License (MIT). Please see License File for more information.

solution-forest/workflow-engine-laravel 适用场景与选型建议

solution-forest/workflow-engine-laravel 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2 次下载、GitHub Stars 达 4, 最近一次更新时间为 2025 年 05 月 29 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「automation」 「state-machine」 「orchestration」 「laravel-package」 「solutionforest」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 solution-forest/workflow-engine-laravel 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 solution-forest/workflow-engine-laravel 我们能提供哪些服务?
定制开发 / 二次开发

基于 solution-forest/workflow-engine-laravel 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 4
  • 点击次数: 29
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 4
  • Watchers: 2
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-05-29