PHP code example of litepie / actions

1. Go to this page and download the library: Download litepie/actions 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 / actions example snippets




namespace App\Actions;

use App\Models\User;
use Litepie\Actions\StandardAction;

class CreateUserAction extends StandardAction
{
    protected function rules(): array
    {
        return [
            'name' => 'this->data['name'],
            'email' => $this->data['email'],
            'password' => bcrypt($this->data['password']),
        ]);
    }
}

// Execute the action
$result = CreateUserAction::execute(null, [
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => 'password123'
], $currentUser);

if ($result->isSuccess()) {
    $user = $result->getData();
    echo "User created: " . $user->name;
} else {
    echo "Error: " . $result->getMessage();
}

$result = CreateUserAction::make(null, $userData, $currentUser)
    ->cached('user-creation', 1800)
    ->retries(3)
    ->timeout(60)
    ->executeWithRetry();

use Litepie\Actions\BaseAction;

class SimpleAction extends BaseAction
{
    protected function handle(): mixed
    {
        return ['message' => 'Action completed'];
    }
}

use Litepie\Actions\StandardAction;

class StandardUserAction extends StandardAction
{
    protected function rules(): array
    {
        return ['email' => '

use Litepie\Actions\CompleteAction;

class ComplexOrderAction extends CompleteAction
{
    protected function rules(): array
    {
        return ['order_id' => '],
            ['action' => UpdateInventoryAction::class],
        ] : [];
    }

    protected function getNotifications(): array
    {
        return [
            [
                'recipients' => User::admins()->get(),
                'class' => OrderProcessedNotification::class
            ]
        ];
    }

    protected function handle(): Order
    {
        $order = Order::find($this->data['order_id']);
        $order->update(['status' => 'processed']);
        return $order;
    }
}

use Litepie\Actions\BaseAction;
use Litepie\Actions\Traits\AuthorizesActions;
use Litepie\Actions\Traits\LogsActions;

class CustomAction extends BaseAction
{
    use AuthorizesActions, LogsActions;

    protected function handle(): mixed
    {
        // Your custom logic
    }
}

class ProcessOrderAction extends CompleteAction
{
    protected function getSubActions(string $timing): array
    {
        if ($timing === 'before') {
            return [
                [
                    'action' => ValidateInventoryAction::class,
                    'data' => ['check_stock' => true],
                ],
            ];
        }

        if ($timing === 'after') {
            return [
                [
                    'action' => SendInvoiceAction::class,
                    'condition' => fn($data) => $data['send_invoice'] ?? false,
                ],
                [
                    'action' => UpdateInventoryAction::class,
                    'continue_on_failure' => true,
                ],
                [
                    'action' => NotifyCustomerAction::class,
                    'data' => ['template' => 'order_confirmation'],
                ],
            ];
        }

        return [];
    }
}

class CreateUserAction extends CompleteAction
{
    protected function getFormFields(): array
    {
        return [
            [
                'name' => 'name',
                'type' => 'text',
                'label' => 'Full Name',
                '   'type' => 'select',
                'label' => 'User Role',
                'options' => [
                    'user' => 'Regular User',
                    'admin' => 'Administrator',
                ],
            ],
        ];
    }

    protected function getFormValidationRules(): array
    {
        return [
            'name' => '

use Litepie\Actions\Facades\ActionManager;

// Register actions
ActionManager::register('create-user', CreateUserAction::class);
ActionManager::register('process-order', ProcessOrderAction::class);

// Execute registered actions
$result = ActionManager::execute('create-user', $userData);

// Chain multiple actions
$results = ActionManager::chain([
    ['name' => 'create-user', 'data' => $userData],
    ['name' => 'send-welcome-email', 'use_previous_result' => true],
]);

// Execute actions in parallel
$results = ActionManager::parallel([
    ['name' => 'create-user', 'data' => $user1Data],
    ['name' => 'create-user', 'data' => $user2Data],
]);

// Get execution statistics
$stats = ActionManager::getStatistics();

use Litepie\Actions\Batch\ActionBatch;

$batch = ActionBatch::make()
    ->add(new CreateUserAction(null, $user1Data))
    ->add(new CreateUserAction(null, $user2Data))
    ->add(new CreateUserAction(null, $user3Data))
    ->concurrent(3)
    ->stopOnFailure(false)
    ->execute();

$successful = $batch->getSuccessful();
$failed = $batch->getFailed();
$allSuccessful = $batch->isAllSuccessful();

use Litepie\Actions\Pipeline\ActionPipeline;

$result = ActionPipeline::make()
    ->send($initialData)
    ->through([
        ValidateDataAction::class,
        ProcessDataAction::class,
        SaveDataAction::class,
    ])
    ->via([
        LoggingMiddleware::class,
        RateLimitMiddleware::class,
    ])
    ->execute();

use Litepie\Actions\Conditional\ConditionalAction;

$result = ConditionalAction::make()
    ->when(fn($data) => $data['user_type'] === 'premium')
    ->then(CreatePremiumUserAction::class)
    ->otherwise(CreateRegularUserAction::class)
    ->with($userData)
    ->execute();

// Or using helper function
$result = action_when(fn($data) => $data['amount'] > 1000)
    ->then(ProcessLargeOrderAction::class)
    ->otherwise(ProcessRegularOrderAction::class)
    ->with($orderData)
    ->execute();

use Litepie\Actions\Middleware\LoggingMiddleware;
use Litepie\Actions\Middleware\RateLimitMiddleware;

// Built-in middleware
class MyAction extends BaseAction
{
    // Middleware will be applied automatically in pipelines
}

// Custom middleware
class CustomMiddleware extends ActionMiddleware
{
    public function handle(ActionContract $action, Closure $next): mixed
    {
        // Before action execution
        $result = $next($action);
        // After action execution
        return $result;
    }
}

// Enable caching for specific executions
$result = CreateUserAction::make($model, $data)
    ->cached('user-creation-' . $data['email'], 3600)
    ->execute();

// Cache with custom key and TTL
$result = ProcessReportAction::make()
    ->with($reportData)
    ->cached('report-' . $reportId, 7200)
    ->execute();

// Clear cached results
$action->clearCache();

// Disable caching for this execution
$result = $action->fresh()->execute();

// Configure retries
$result = UnstableApiAction::make()
    ->with($apiData)
    ->retries(5)
    ->timeout(30)
    ->executeWithRetry();

// Exponential backoff is applied automatically
// Retry delays: 1s, 2s, 4s, 8s, 16s

// Execute asynchronously
CreateUserAction::make($model, $data, $user)->executeAsync();

// Or use Laravel's dispatch
CreateUserAction::dispatch($model, $data, $user);

// Delayed execution
CreateUserAction::executeLater(now()->addMinutes(30), $model, $data, $user);

use Litepie\Actions\Models\ActionLog;

// Query action logs
$logs = ActionLog::inLog('actions')
    ->where('action', 'CreateUser')
    ->where('created_at', '>=', now()->subDays(7))
    ->get();

// Get logs for specific model
$userLogs = ActionLog::forSubject($user)->get();

// Get logs by user
$adminLogs = ActionLog::causedBy($admin)->get();

// Get log properties
$log = ActionLog::first();
$executionTime = $log->getExtraProperty('execution_time');
$userAgent = $log->getExtraProperty('user_agent');

// config/actions.php
return [
    'cache' => [
        'enabled' => true,
        'ttl' => 3600,
        'prefix' => 'action',
    ],
    
    'logging' => [
        'enabled' => true,
        'default_log_name' => 'actions',
        'delete_records_older_than_days' => 365,
    ],
    
    'authorization' => [
        'enabled' => true,
        '

// Execute registered action
$result = action('create-user', $userData);

// Create action batch
$batch = action_batch()
    ->add($action1)
    ->add($action2)
    ->execute();

// Create action pipeline
$result = action_pipeline()
    ->send($data)
    ->through($actions)
    ->execute();

// Conditional action execution
$result = action_when($condition)
    ->then(ActionA::class)
    ->otherwise(ActionB::class)
    ->execute();

// Test your actions
class CreateUserActionTest extends TestCase
{
    /** @test */
    public function it_creates_a_user_successfully()
    {
        $userData = ['name' => 'John', 'email' => '[email protected]'];
        $result = CreateUserAction::execute(null, $userData, $this->user);
        
        $this->assertTrue($result->isSuccess());
        $this->assertInstanceOf(User::class, $result->getData());
    }

    /** @test */
    public function it_validates_

class ProcessOrderAction extends CompleteAction
{
    protected function rules(): array
    {
        return [
            'order_id' => 'rray
    {
        if ($timing === 'before') {
            return [
                [
                    'action' => ValidateInventoryAction::class,
                    'data' => ['strict_check' => true],
                ],
                [
                    'action' => CalculateShippingAction::class,
                    'condition' => fn($data) => $data['shipping_s,
                    'continue_on_failure' => true,
                ],
                [
                    'action' => CreateShippingLabelAction::class,
                    'condition' => fn($data) => $data['shipping_order = Order::find($this->data['order_id']);
        
        $order->update([
            'status' => 'processing',
            'processed_at' => now(),
            'processed_by' => $this->user->id,
        ]);

        return $order;
    }

    protected function getDescription(string $status): string
    {
        $orderId = $this->data['order_id'];
        return "Order #{$orderId} processing " . ($status === 'success' ? 'completed' : 'failed');
    }
}

$users = collect($csvData);
$batch = ActionBatch::make()->concurrent(10);

foreach ($users->chunk(100) as $userChunk) {
    foreach ($userChunk as $userData) {
        $batch->add(new CreateUserAction(null, $userData, $admin));
    }
}

$results = $batch->execute();

// Handle results
$successful = $batch->getSuccessful();
$failed = $batch->getFailed();

Log::info("Batch import completed", [
    'total' => $results->count(),
    'successful' => $successful->count(),
    'failed' => $failed->count(),
]);
bash
php artisan vendor:publish --tag=actions-config
bash
php artisan migrate
bash
php artisan make:action CreateUserAction --validation --cacheable