定制 juanparati/laravel-sync-workflow 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

juanparati/laravel-sync-workflow

Composer 安装命令:

composer require juanparati/laravel-sync-workflow

包简介

A library for executing synchronous workflows in Laravel

README 文档

README

test

Laravel Synchronous Workflows

A robust library for executing reproducible synchronous workflows with seamless event sourcing capabilities in Laravel.

Workflow activities are executed sequentially within a single process and are not distributed across multiple instances or jobs.

Each time that an activity is executed, its input is passed to the next activity in the workflow, and objects are decoupled from their original reference to avoid non-desired mutability.

For distributed asynchronous workflows, see Laravel Workflow.

Key features include:

  • Synchronous workflow execution
  • Event sourcing capabilities
  • Comprehensive workflow history tracking
  • Workflow replay functionality
  • Automatic object reference decoupling
  • Relative time management
  • Unique workflow locking
  • Controlled exceptions for graceful workflow halting

This library is inspired by Laravel Workflow and Laravel Saga.

Installation

composer require juanparati/laravel-sync-workflow

Publish migrations and configuration files (required for event sourcing):

artisan vendor:publish --tag=laravel-sync-workflow

Run migrations:

artisan migrate

Usage

Basic Workflow Example

Here's a simple workflow that processes user registration:

<?php

namespace App\SyncWorkflows;

use App\SyncWorkflows\UserRegistration\SendWelcomeEmail;
use App\SyncWorkflows\UserRegistration\CreateUserProfile;
use Juanparati\SyncWorkflow\SyncWorkflow;

class UserRegistrationWorkflow extends SyncWorkflow
{
    protected User $user;

    public function __construct(User|array $user)
    {
        $this->user = $user instanceof User ? $user : new User($user);
    }

    public function handle()
    {
        // Create user profile
        $profile = $this->executor()->runActivity(
            CreateUserProfile::class,
            $this->user
        );

        // Send welcome email
        $this->executor()->runActivity(
            SendWelcomeEmail::class,
            $this->user
        );

        return ['user_id' => $profile->id, 'status' => 'registered'];
    }
}

or as a chain of activities:

<?php

namespace App\SyncWorkflows;

use App\SyncWorkflows\UserRegistration\SendWelcomeEmail;
use App\SyncWorkflows\UserRegistration\CreateUserProfile;
use Juanparati\SyncWorkflow\Contracts\WithEventSourcing;
use Juanparati\SyncWorkflow\SyncWorkflow;

// When implementing WithEventSourcing, the workflow will be persisted in the database
// and its execution history will be available for replay.
class UserRegistrationWorkflow extends SyncWorkflow implements WithEventSourcing
{

    protected User $user;

    public function __construct(User|array $user)
    {
        $this->user = $user instanceof User ? $user : new User($user);
    } 
       
    public function handle()
    {
        $profile = $this->executor()->runChainedActivities([
            CreateUserProfile::class,
            SendWelcomeEmail::class,
        ], $this->user);    // The output of one activity is the input of the next
              
        return ['user_id' => $profile->id, 'status' => 'registered'];
    }
}

Activity Example

Activities contain the actual business logic:

<?php

namespace App\SyncWorkflows\UserRegistration;

use App\Models\User;
use Juanparati\SyncWorkflow\SyncActivity;

class CreateUserProfile extends SyncActivity
{
    public function __construct(protected User $user) {}

    public function handle()
    {   
        // Use relativeNow instead of now() to ensure consistent timestamps during workflow replay
        // by preserving the original execution time.
        $this->user->created_at = $this->executor()->relativeNow();
        $this->user->email_verified = true;
        $this->user->save();
            
        return $this->user;
    }
}

Running Workflows

Execute a workflow programmatically:

use Juanparati\SyncWorkflow\SyncExecutor;

$result = SyncExecutor::dispatch(
    new UserRegistrationWorkflow(['email' => 'user@example.com', 'name' => 'John Doe'])
);

// Access the result
echo "User registered with ID: " . $result->id;

or alternatively:

use Juanparati\SyncWorkflow\SyncExecutor;

$workflow = SyncExecutor::make()
    ->load(new UserRegistrationWorkflow(['email' => 'user@example.com', 'name' => 'John Doe']));
    
echo "Workflow ID: " . $workflow->getId();

$workflow->run();

echo "Workflow finished at " . $workflow->getExecutionTime()['endedAt'];

$result = $workflow->getResult();

// Access the result
echo "User registered with ID: " . $result->id;

Controlled Exceptions

To gracefully halt workflow execution, you can throw a SyncWorkflowControlledException from within an activity:

<?php

namespace App\SyncWorkflows\OrderProcessing;

use Juanparati\SyncWorkflow\Exceptions\SyncWorkflowControlledException;
use Juanparati\SyncWorkflow\SyncActivity;
use App\Services\PaymentService;
use Exception;

class ValidatePayment extends SyncActivity
{
    public function handle()
    {   
        $paymentPermission = PaymentService::obtainPermission($this->input);
        
        if (!$paymentPermission) {
            throw (new SyncWorkflowControlledException('Permission denied'))
                ->addError(['info' => $this->input]);
        }
        
        return $paymentPermission;                
    }
}

You can handle the exception in your workflow:

try {
    SyncExecutor::dispatch(new OrderProcessingWorkflow($order));
} catch (SyncWorkflowControlledException $e) {
    \Log::warning('Order process cancelled: ' . $e->getMessage(), $e->getErrors());
} catch (Exception $e) {
    \Log::error('Unable to process order: ' . $e->getMessage());   
    throw $e;
}

Workflow locking

Use the HasLock trait to automatically acquire a lock before executing a workflow:

<?php

namespace App\SyncWorkflows;

use App\SyncWorkflows\UserRegistration\SendWelcomeEmail;
use App\SyncWorkflows\UserRegistration\CreateUserProfile;
use Juanparati\SyncWorkflow\Concerns\HasLock;
use Juanparati\SyncWorkflow\SyncWorkflow;

class UserRegistrationWorkflow extends SyncWorkflow
{
    use HasLock;

    protected function uniqueId() {
        return 'my_lock_key';
    }
    ...
}

Use the uniqueId method to define a unique identifier for the workflow, otherwise the class name is used by default.

When the lock was already acquired by another workflow the exception SyncWorkflowLockException is thrown.

Commands

Generate a new workflow

artisan make:sync-workflow MyWorkflow

The workflow will be created in the app/SyncWorkflows directory.

Generate a new activity

artisan make:sync-workflow-activity MyWorkflow/MyFirstActivity

Replay a workflow

artisan sync-workflow:replay [workflow-id]

View workflow state

artisan sync-workflow:view [workflow-id]

juanparati/laravel-sync-workflow 适用场景与选型建议

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

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 773
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 25
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-08-25