Back to Documentation

PHP SDK Examples

Real-world examples showing how to use the OddSockets PHP SDK in production applications

View Basic Example
Basic Usage
Available
Simple example showing how to connect, subscribe to a channel, and publish messages using the core PHP SDK functionality with ReactPHP.
<?php

require_once 'vendor/autoload.php';

use OddSockets\OddSockets;
use React\EventLoop\Loop;

// Create client
$client = OddSockets::create('ak_live_1234567890abcdef');

// Get channel
$channel = $client->channel('my-channel');

// Subscribe to messages
$channel->subscribe(function ($message) {
    echo "Received: " . json_encode($message) . "\n";
});

// Publish a message
$channel->publish('Hello, World!');

// Start the event loop
Loop::get()->run();
Advanced Configuration
Available
Demonstrates advanced configuration options including custom settings, event handling, and Promise-based operations.
<?php

use OddSockets\Config\OddSocketsConfig;

$config = OddSocketsConfig::builder('ak_live_1234567890abcdef')
    ->userId('user123')
    ->autoConnect(false)
    ->reconnectAttempts(3)
    ->timeout(15)
    ->build();

$client = OddSockets::create($config);

$client->on('connected', function () {
    echo "Connected to OddSockets!\n";
});

$client->connect()->then(function () {
    echo "Connection established!\n";
});
Laravel Integration
Available
Shows how to integrate OddSockets with Laravel applications using service providers and dependency injection.
<?php

namespace App\Services;

use OddSockets\OddSockets;
use React\EventLoop\Loop;

class OddSocketsService
{
    private $client;
    
    public function __construct()
    {
        $this->client = OddSockets::create(config('oddsockets.api_key'));
        
        $this->client->on('connected', function () {
            \Log::info('OddSockets connected');
        });
    }
    
    public function publishToChannel(string $channel, $message)
    {
        $channel = $this->client->channel($channel);
        
        return $channel->publish($message);
    }
}
ReactPHP Integration
Available
Complete ReactPHP application example showing how to build real-time applications with HTTP server and WebSocket integration.
<?php

use OddSockets\OddSockets;
use React\EventLoop\Loop;
use React\Http\HttpServer;
use React\Http\Message\Response;

$loop = Loop::get();

// Create OddSockets client
$oddSockets = OddSockets::create('ak_live_1234567890abcdef', $loop);

// Create HTTP server
$server = new HttpServer($loop, function ($request) use ($oddSockets) {
    $channel = $oddSockets->channel('web-events');
    
    // Publish web request event
    $channel->publish([
        'type' => 'http_request',
        'method' => $request->getMethod(),
        'uri' => $request->getUri()->getPath(),
        'timestamp' => time()
    ]);
    
    return new Response(200, [], 'Hello from ReactPHP + OddSockets!');
});

$loop->run();
Bulk Operations
Available
Demonstrates bulk message publishing, batch operations, and efficient handling of multiple channels simultaneously.
<?php

$messages = [
    [
        'channel' => 'notifications',
        'message' => ['type' => 'info', 'text' => 'System update available'],
        'options' => ['ttl' => 3600]
    ],
    [
        'channel' => 'alerts',
        'message' => ['type' => 'warning', 'text' => 'High CPU usage detected'],
        'options' => ['ttl' => 1800]
    ],
    [
        'channel' => 'logs',
        'message' => ['level' => 'info', 'message' => 'User logged in'],
        'options' => []
    ]
];

$client->publishBulk($messages)->then(function ($results) {
    echo "Bulk publish results:\n";
    foreach ($results as $i => $result) {
        if ($result['success']) {
            echo "  Message $i: Success\n";
        } else {
            echo "  Message $i: Failed - " . $result['error'] . "\n";
        }
    }
});
Error Handling
Available
Comprehensive error handling patterns, exception management, and robust reconnection strategies for production applications.
<?php

$client->on('error', function ($error) {
    echo "Error: " . $error->getMessage() . "\n";
});

$client->on('reconnecting', function ($data) {
    echo "Reconnecting... Attempt " . $data['attempt'] . "/" . $data['maxAttempts'] . "\n";
});

$channel = $client->channel('error-demo');

$channel->subscribe($callback)
    ->then(function () {
        echo "Successfully subscribed\n";
    })
    ->otherwise(function ($error) {
        echo "Subscription failed: " . $error->getMessage() . "\n";
        
        // Implement retry logic
        if ($error instanceof \OddSockets\Exception\TimeoutException) {
            // Handle timeout specifically
            echo "Retrying subscription...\n";
        }
    });