PHP code example of litepie / flow

1. Go to this page and download the library: Download litepie/flow library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

litepie / flow example snippets




// 1. Create a State Machine
namespace App\StateMachines;

use Litepie\Flow\StateMachine\AbstractStateMachine;

class OrderStatusStateMachine extends AbstractStateMachine
{
    public function transitions(): array
    {
        return [
            'process' => ['from' => 'pending', 'to' => 'processing'],
            'ship' => ['from' => 'processing', 'to' => 'shipped'],
            'deliver' => ['from' => 'shipped', 'to' => 'delivered'],
            'cancel' => ['from' => ['pending', 'processing'], 'to' => 'cancelled'],
        ];
    }

    public function stateLabels(): array
    {
        return [
            'pending' => 'Pending Payment',
            'processing' => 'Being Processed',
            'shipped' => 'Shipped',
            'delivered' => 'Delivered',
            'cancelled' => 'Cancelled',
        ];
    }
}

// 2. Add to your Model
use Litepie\Flow\Traits\HasStateMachine;

class Order extends Model
{
    use HasStateMachine;

    protected $stateMachines = [
        'status' => OrderStatusStateMachine::class,
    ];
}

// 3. Use it
$order = Order::create(['status' => 'pending']);

// Check state
if ($order->stateMachine('status')->is('pending')) {
    // Change state
    $order->status = 'processing';
    $order->save();
}

// Get label
echo $order->stateMachine('status')->getCurrentStateLabel(); // "Being Processed"



namespace App\Actions;

use Litepie\Actions\BaseAction;
use Litepie\Actions\Traits\ValidatesInput;
use Litepie\Actions\Contracts\ActionResult;

class ProcessPaymentAction extends BaseAction
{
    use ValidatesInput;

    protected string $name = 'process_payment';

    public function execute(array $context = []): ActionResult
    {
        $validated = $this->validateContext($context);
        
        // Your payment processing logic here
        $result = $this->processPayment($validated);
        
        return $result['success']
            ? $this->success($result, 'Payment processed successfully')
            : $this->failure($result['errors'], 'Payment processing failed');
    }

    protected function rules(): array
    {
        return [
            'amount' => '



namespace App\Workflows;

use Litepie\Flow\Workflows\Workflow;
use Litepie\Flow\States\State;
use Litepie\Flow\Transitions\Transition;

class OrderWorkflow
{
    public static function create(): Workflow
    {
        $workflow = new Workflow('order_processing', 'Order Processing Workflow');

        // Define states
        $pending = new State('pending', 'Pending', true);        // Initial state
        $processing = new State('processing', 'Processing');
        $shipped = new State('shipped', 'Shipped');
        $delivered = new State('delivered', 'Delivered', false, true); // Final state

        // Add states to workflow
        $workflow->addState($pending)
                 ->addState($processing)
                 ->addState($shipped)
                 ->addState($delivered);

        // Define transitions with actions
        $processTransition = new Transition('pending', 'processing', 'process');
        $processTransition->addAction(new \App\Actions\ProcessPaymentAction());

        $shipTransition = new Transition('processing', 'shipped', 'ship');
        $deliverTransition = new Transition('shipped', 'delivered', 'deliver');

        // Add transitions to workflow
        $workflow->addTransition($processTransition)
                 ->addTransition($shipTransition)
                 ->addTransition($deliverTransition);

        return $workflow;
    }
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Litepie\Flow\Traits\HasWorkflow;
use Litepie\Flow\Contracts\Workflowable;

class Order extends Model implements Workflowable
{
    use HasWorkflow;

    protected $fillable = ['customer_id', 'total', 'state'];

    public function getWorkflowName(): string
    {
        return 'order_processing';
    }

    protected function getWorkflowStateColumn(): string
    {
        return 'state';
    }
}



namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Litepie\Flow\Facades\Flow;
use App\Workflows\OrderWorkflow;

class WorkflowServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Flow::register('order_processing', OrderWorkflow::create());
    }
}

'providers' => [
    // Other providers...
    App\Providers\WorkflowServiceProvider::class,
],

// Create a new order
$order = Order::create([
    'customer_id' => 1,
    'total' => 99.99,
    'state' => 'pending'
]);

// Check available transitions
$transitions = $order->getAvailableTransitions();

// Check if a specific transition is possible
if ($order->canTransitionTo('processing')) {
    // Transition to the next state with context data
    $order->transitionTo('processing', [
        'amount' => $order->total,
        'payment_method' => 'credit_card',
        'order_id' => $order->id
    ]);
}

// Get current state
$currentState = $order->getCurrentState();
echo $currentState->getLabel(); // "Processing"

// Get workflow history
$history = $order->getWorkflowHistory();

// Listen to workflow events
Event::listen('workflow.order_processing.transition.process', function ($event) {
    Log::info('Order transitioned to processing', [
        'order_id' => $event->getSubject()->id,
        'from' => $event->getFromState(),
        'to' => $event->getToState()
    ]);
});

// Conditional transitions
if ($order->getCurrentState()->getName() === 'pending' && $order->total > 100) {
    $order->transitionTo('processing', ['expedite' => true]);
}

// Bulk state updates
Order::whereIn('id', [1, 2, 3])
     ->each(function ($order) {
         if ($order->canTransitionTo('shipped')) {
             $order->transitionTo('shipped');
         }
     });

return [
    // Database table names
    'tables' => [
        'workflows' => 'workflows',
        'workflow_states' => 'workflow_states',
        'workflow_transitions' => 'workflow_transitions',
        'workflow_logs' => 'workflow_logs',
    ],

    // Event handling
    'events' => [
        'enabled' => true,
        'prefix' => 'workflow',
    ],

    // Logging configuration
    'logging' => [
        'enabled' => true,
        'channel' => env('WORKFLOW_LOG_CHANNEL', 'default'),
    ],

    // Action configuration
    'actions' => [
        'namespace' => 'App\\Actions',
        'timeout' => 300, // seconds
    ],
];

// In EventServiceProvider
protected $listen = [
    'workflow.order_processing.enter.processing' => [
        NotifyCustomerListener::class,
    ],
    'workflow.order_processing.transition.ship' => [
        GenerateTrackingNumberListener::class,
    ],
];
bash
php artisan vendor:publish --tag="flow-migrations"
php artisan migrate
bash
php artisan vendor:publish --tag="flow-config"