PHP code example of intelfric / n8n-php-automation

1. Go to this page and download the library: Download intelfric/n8n-php-automation 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/ */

    

intelfric / n8n-php-automation example snippets


use DrMsigwa\Automation\Models\Flow;
use DrMsigwa\Automation\Nodes\HttpRequestNode;
use DrMsigwa\Automation\Nodes\EmailNode;

// Create a new flow
$flow = Flow::create([
    'name' => 'Send Weather Alert',
    'description' => 'Fetch weather data and send email alert',
    'status' => 'active',
]);

// Add nodes to the flow
$httpNode = $flow->nodes()->create([
    'type' => HttpRequestNode::class,
    'name' => 'Fetch Weather',
    'config' => [
        'method' => 'GET',
        'url' => 'https://api.weather.com/current',
    ],
]);

$emailNode = $flow->nodes()->create([
    'type' => EmailNode::class,
    'name' => 'Send Alert',
    'config' => [
        'to' => '[email protected]',
        'subject' => 'Weather Update',
        'body' => 'Current weather: {{http_body}}',
    ],
]);

// Connect nodes
$flow->connections()->create([
    'source_node_id' => $httpNode->id,
    'target_node_id' => $emailNode->id,
]);

use DrMsigwa\Automation\Engine\FlowRunner;

$runner = new FlowRunner($flow);
$result = $runner->run(['city' => 'New York']);

dd($result);

[
    'type' => HttpRequestNode::class,
    'config' => [
        'method' => 'POST',
        'url' => 'https://api.example.com/data',
        'headers' => ['Authorization' => 'Bearer token'],
        'body' => ['key' => 'value'],
        'timeout' => 30,
    ],
]

[
    'type' => EmailNode::class,
    'config' => [
        'to' => '[email protected]',
        'subject' => 'Hello World',
        'body' => 'Email content here',
        'from' => '[email protected]', // optional
    ],
]

[
    'type' => DelayNode::class,
    'config' => [
        'seconds' => 5,
    ],
]

[
    'type' => ConditionNode::class,
    'config' => [
        'left' => '{{http_status}}',
        'operator' => '==',
        'right' => 200,
    ],
]

[
    'type' => DatabaseQueryNode::class,
    'config' => [
        'table' => 'users',
        'operation' => 'select',
        'conditions' => [
            ['column' => 'status', 'operator' => '=', 'value' => 'active'],
        ],
        'fields' => ['id', 'name', 'email'],
        'limit' => 10,
    ],
]



namespace App\Automation\Nodes;

use DrMsigwa\Automation\Contracts\NodeInterface;

class SlackNotificationNode implements NodeInterface
{
    public function execute(array $data): array
    {
        $config = $data['config'] ?? [];
        $message = $config['message'] ?? '';
        
        // Your implementation here
        // Send message to Slack
        
        return [
            'slack_message_sent' => true,
            'slack_timestamp' => now()->toISOString(),
        ];
    }

    public function getDescription(): array
    {
        return [
            'name' => 'Slack Notification',
            'description' => 'Sends notifications to Slack',
            'icon' => 'message-square',
            'category' => 'notification',
            'inputs' => [
                ['name' => 'message', 'type' => 'string', '

'nodes' => [
    // Built-in nodes
    \DrMsigwa\Automation\Nodes\HttpRequestNode::class,
    \DrMsigwa\Automation\Nodes\EmailNode::class,
    // ... others
    
    // Your custom nodes
    \App\Automation\Nodes\SlackNotificationNode::class,
],

use DrMsigwa\Automation\Facades\Automation;

Automation::register(\App\Automation\Nodes\SlackNotificationNode::class);

$emailNode = $flow->nodes()->create([
    'type' => EmailNode::class,
    'config' => [
        'to' => '{{user_email}}',
        'subject' => 'Order #{{order_id}} Confirmed',
        'body' => 'Thank you {{user_name}}! Your order status: {{http_status}}',
    ],
]);

// In your EventServiceProvider
protected $listen = [
    \DrMsigwa\Automation\Events\FlowStarted::class => [
        \App\Listeners\LogFlowStart::class,
    ],
    \DrMsigwa\Automation\Events\NodeExecuted::class => [
        \App\Listeners\LogNodeExecution::class,
    ],
    \DrMsigwa\Automation\Events\FlowCompleted::class => [
        \App\Listeners\NotifyFlowCompletion::class,
    ],
];

'queue' => [
    'enabled' => true,
    'connection' => 'redis',
    'queue' => 'automation',
],

use DrMsigwa\Automation\Engine\FlowRunner;
use DrMsigwa\Automation\Models\Flow;

$flow = Flow::find(1);
$runner = new FlowRunner($flow);
$result = $runner->run(['key' => 'value']);

use DrMsigwa\Automation\Models\Flow;
use DrMsigwa\Automation\Engine\FlowRunner;

protected function schedule(Schedule $schedule)
{
    // Run a specific flow every minute
    $schedule->call(function () {
        $flow = Flow::find(1);
        (new FlowRunner($flow))->run();
    })->everyMinute();
    
    // Run daily at midnight
    $schedule->call(function () {
        $flow = Flow::find(2);
        (new FlowRunner($flow))->run();
    })->daily();
    
    // Run every hour
    $schedule->call(function () {
        $flow = Flow::find(3);
        (new FlowRunner($flow))->run();
    })->hourly();
}

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        $activeFlows = Flow::where('status', 'active')->get();
        
        foreach ($activeFlows as $flow) {
            try {
                (new FlowRunner($flow))->run();
            } catch (\Exception $e) {
                \Log::error("Flow {$flow->id} failed: " . $e->getMessage());
            }
        }
    })->everyFiveMinutes();
}



namespace App\Jobs;

use DrMsigwa\Automation\Models\Flow;
use DrMsigwa\Automation\Engine\FlowRunner;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

class ExecuteFlowJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;
    
    public function __construct(public int $flowId, public array $data = [])
    {
    }
    
    public function handle()
    {
        $flow = Flow::find($this->flowId);
        if ($flow) {
            (new FlowRunner($flow))->run($this->data);
        }
    }
}

protected function schedule(Schedule $schedule)
{
    $schedule->job(new ExecuteFlowJob(1))->everyMinute();
}

// In your routes/api.php or controller
Route::post('/webhook/trigger-flow/{flowId}', function ($flowId) {
    $flow = Flow::find($flowId);
    
    if (!$flow) {
        return response()->json(['error' => 'Flow not found'], 404);
    }
    
    $data = request()->all();
    $runner = new FlowRunner($flow);
    $result = $runner->run($data);
    
    return response()->json(['success' => true, 'result' => $result]);
});

[
    'type' => LoopNode::class,
    'config' => [
        'items' => [1, 2, 3, 4, 5],
        'max_iterations' => 1000, // Safety limit (default: 1000)
    ],
]

use DrMsigwa\Automation\Models\Flow;
use DrMsigwa\Automation\Engine\FlowRunner;

$flow = Flow::find(1);
$runner = new FlowRunner($flow);

try {
    $result = $runner->run([
        'user_id' => 123,
        'action' => 'purchase',
    ]);
    
    $execution = $runner->getExecution();
    $logger = $runner->getLogger();
    
    echo "Execution ID: {$execution->id}\n";
    echo "Status: {$execution->status}\n";
    
} catch (\Exception $e) {
    echo "Flow failed: " . $e->getMessage();
}

use DrMsigwa\Automation\Models\Execution;

$execution = Execution::find(1);

foreach ($execution->logs as $log) {
    echo "[{$log['level']}] {$log['message']}\n";
}

// Only execute flows with specific status
$activeFlows = Flow::where('status', 'active')->get();

foreach ($activeFlows as $flow) {
    $runner = new FlowRunner($flow);
    $runner->run();
}
bash
composer 
bash
php artisan vendor:publish --tag=automation-config
bash
php artisan vendor:publish --tag=automation-migrations
php artisan migrate
bash
php artisan automation:run 1
php artisan automation:run 1 --data='{"city":"New York"}'
bash
php artisan automation:run {flow_id}
php artisan automation:run 1 --data='{"user_id":123}'