Skip to content

Examples Collection

Jean-Marc Strauven edited this page Aug 6, 2025 · 2 revisions

πŸ“š Examples Collection

This page provides a comprehensive collection of real-world examples demonstrating Laravel Statecraft's capabilities. Each example includes complete YAML configurations, model setup, guards, actions, and tests.

🎯 Featured Examples

Complete e-commerce order processing workflow

A comprehensive example covering the entire order lifecycle from creation to delivery, including:

  • Payment processing with multiple payment methods
  • Inventory management and reservation
  • Shipping integration with tracking
  • Customer notifications and refund handling
  • Complex guard logic and conditional transitions

Use Cases: E-commerce platforms, order management systems, fulfillment workflows

Content management and publishing workflow

A sophisticated content management workflow featuring:

  • Multi-step editorial review process
  • Role-based permissions and approvals
  • Content scheduling and publication
  • Revision tracking and rollback capabilities
  • SEO and metadata management

Use Cases: CMS platforms, blog management, editorial workflows, content publishing

Subscription lifecycle management

A complete subscription management system including:

  • Trial period management
  • Payment processing and billing cycles
  • Subscription upgrades and downgrades
  • Payment failure handling and dunning
  • Cancellation and reactivation flows

Use Cases: SaaS platforms, membership sites, subscription services

Advanced event handling and integration

Demonstrates comprehensive event system usage:

  • Real-time notifications and webhooks
  • Analytics and metrics collection
  • External system integrations
  • Audit logging and compliance
  • Custom event listeners and broadcasting

Use Cases: Real-time applications, integration platforms, audit systems

πŸ—οΈ Quick Start Examples

Simple State Machine

Perfect for learning the basics:

# Simple approval workflow
name: SimpleApproval
model: App\Models\Document
initial_state: draft

states:
  - name: draft
    description: Document is being edited
  - name: pending
    description: Awaiting approval
  - name: approved
    description: Document approved
  - name: rejected
    description: Document rejected

transitions:
  - name: submit
    from: draft
    to: pending
    
  - name: approve
    from: pending
    to: approved
    guard: IsManager
    
  - name: reject
    from: pending
    to: rejected
    guard: IsManager

Multi-State Transitions

Handle multiple source states:

transitions:
  - name: cancel
    from: [draft, pending, approved]
    to: cancelled
    action: NotifyStakeholders

Complex Guard Logic

Combine multiple conditions:

transitions:
  - name: auto_approve
    from: pending
    to: approved
    guard:
      and:
        - HasMinimumAmount
        - IsRegularCustomer
        - not: RequiresManualReview

🎨 By Industry

E-commerce

  • Order Processing - Complete order fulfillment workflow
  • Inventory Management - Stock reservation and allocation
  • Customer Service - Support ticket resolution workflow
  • Product Catalog - Product approval and publishing

SaaS Platforms

  • User Onboarding - Multi-step user registration and verification
  • Subscription Management - Billing cycles and plan changes
  • Feature Rollouts - Gradual feature deployment workflow
  • Support Tickets - Customer support case management

Content Management

  • Editorial Workflow - Content creation, review, and publishing
  • Media Processing - File upload, processing, and approval
  • Comment Moderation - User-generated content approval
  • SEO Optimization - Content optimization workflow

Financial Services

  • Loan Applications - Multi-step approval process
  • KYC Compliance - Customer verification workflow
  • Transaction Processing - Payment validation and settlement
  • Risk Assessment - Automated risk evaluation

πŸ”§ By Complexity

Beginner Examples

Start with these simple workflows:

Document Approval

states: [draft, pending, approved, rejected]
transitions:
  - {name: submit, from: draft, to: pending}
  - {name: approve, from: pending, to: approved, guard: IsManager}
  - {name: reject, from: pending, to: rejected, guard: IsManager}

Task Management

states: [todo, in_progress, review, done]
transitions:
  - {name: start, from: todo, to: in_progress}
  - {name: finish, from: in_progress, to: review}
  - {name: complete, from: review, to: done, guard: IsAssignee}

Intermediate Examples

More complex business logic:

Invoice Processing

states: [draft, sent, paid, overdue, cancelled]
transitions:
  - name: send
    from: draft
    to: sent
    guard: HasValidItems
    action: SendInvoiceEmail
    
  - name: pay
    from: [sent, overdue]
    to: paid
    guard: PaymentValidation
    action: ProcessPayment
    
  - name: mark_overdue
    from: sent
    to: overdue
    action: SendReminderEmail

Advanced Examples

Complex workflows with multiple conditions:

Employee Onboarding

states: [applied, screening, interview, background_check, offer, hired, rejected]
transitions:
  - name: screen
    from: applied
    to: screening
    guard:
      and:
        - HasRequiredSkills
        - PassesInitialFilter
        
  - name: schedule_interview
    from: screening
    to: interview
    guard:
      or:
        - IsRecommended
        - HasExceptionalProfile
    action: ScheduleInterviewAction
    
  - name: make_offer
    from: background_check
    to: offer
    guard:
      and:
        - PassedBackgroundCheck
        - InterviewScoreAboveThreshold
        - BudgetAvailable
    action: PrepareOfferAction

πŸ“‹ Example Categories

By Pattern

Linear Workflows

Sequential steps with no branching:

  • User registration β†’ verification β†’ activation
  • Order β†’ payment β†’ fulfillment β†’ delivery

Branching Workflows

Multiple possible paths:

  • Application β†’ approved/rejected
  • Content β†’ published/archived/deleted

Parallel Workflows

Multiple independent processes:

  • Order processing + inventory update
  • Content creation + SEO optimization

Loop Workflows

Repeating cycles:

  • Subscription billing cycles
  • Periodic review processes
  • Retry mechanisms

By Business Function

Approval Processes

  • Document approval
  • Budget approval
  • Leave requests
  • Purchase orders

Content Workflows

  • Article publishing
  • Media processing
  • Comment moderation
  • Translation workflows

Transaction Processing

  • Payment processing
  • Order fulfillment
  • Refund handling
  • Billing cycles

User Management

  • Registration flows
  • Profile verification
  • Permission escalation
  • Account suspension

πŸ§ͺ Testing Examples

Each example includes comprehensive testing strategies:

Unit Tests

public function test_order_can_be_paid()
{
    $order = Order::factory()->pending()->create(['amount' => 100]);
    
    $this->assertTrue($order->canTransitionTo('pay'));
    $order->transitionTo('pay');
    
    $this->assertEquals('paid', $order->getCurrentState());
}

Integration Tests

public function test_complete_order_workflow()
{
    $order = Order::factory()->create();
    
    $order->transitionTo('pay');
    $order->transitionTo('process');
    $order->transitionTo('ship');
    $order->transitionTo('deliver');
    
    $this->assertEquals('delivered', $order->getCurrentState());
    $this->assertCount(4, $order->getStateHistory());
}

Feature Tests

public function test_order_notifications_sent()
{
    Mail::fake();
    
    $order = Order::factory()->create();
    $order->transitionTo('pay');
    
    Mail::assertSent(OrderConfirmationMail::class);
}

πŸ“ˆ Performance Examples

Bulk Operations

// Efficient bulk state transitions
Order::whereIn('id', $orderIds)
    ->chunk(100, function ($orders) {
        foreach ($orders as $order) {
            if ($order->canTransitionTo('auto_cancel')) {
                $order->transitionTo('auto_cancel');
            }
        }
    });

Caching Strategies

// Cache state machine definitions
$stateMachine = Cache::remember(
    "state_machine.{$modelClass}",
    3600,
    fn() => StateMachine::load($modelClass)
);

πŸ”§ Migration Examples

From Manual State Management

// Before: Manual state management
$order->status = 'paid';
$order->paid_at = now();
$order->save();

// After: State machine
$order->transitionTo('pay');

From Simple Enums

// Before: Simple enum
enum OrderStatus: string {
    case PENDING = 'pending';
    case PAID = 'paid';
    case SHIPPED = 'shipped';
}

// After: Full state machine with business logic
$order->transitionTo('pay', ['payment_method' => 'card']);

🎯 Best Practice Examples

Error Handling

try {
    $order->transitionTo('ship');
} catch (TransitionNotAllowedException $e) {
    Log::warning("Cannot ship order {$order->id}: {$e->getMessage()}");
    // Handle gracefully
}

Conditional Logic

guard:
  and:
    - HasValidPayment
    - not: IsBlacklisted
    - or:
        - IsVIPCustomer
        - HasManagerApproval

Event Integration

// Listen for specific state changes
Event::listen(StateTransitioned::class, function ($event) {
    if ($event->model instanceof Order && $event->toState === 'shipped') {
        // Send tracking information
        dispatch(new SendTrackingInfoJob($event->model));
    }
});

πŸš€ Getting Started

  1. Choose an Example - Pick one that matches your use case
  2. Copy the Configuration - Use the YAML as a starting point
  3. Customize Guards and Actions - Implement your business logic
  4. Add Tests - Ensure your workflow works correctly
  5. Iterate and Improve - Refine based on real usage

πŸ“– Example Structure

Each example follows this structure:

  • Overview - What the example demonstrates
  • YAML Configuration - Complete state machine definition
  • Model Setup - Eloquent model configuration
  • Guards - Business rule implementations
  • Actions - Side effect implementations
  • Events - Event handling examples
  • Tests - Comprehensive test suite
  • Usage - How to use in your application

πŸ”— Additional Resources


Ready to explore? Start with the Order Workflow Example for a comprehensive introduction to Laravel Statecraft's capabilities.

Clone this wiki locally