PHP code example of tourze / workerman-user-support

1. Go to this page and download the library: Download tourze/workerman-user-support 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/ */

    

tourze / workerman-user-support example snippets




use Psr\Log\LoggerInterface;
use Psr\SimpleCache\CacheInterface;
use Tourze\Workerman\UserSupport\ConnectionManager;
use Tourze\Workerman\UserSupport\User;
use Workerman\Connection\ConnectionInterface;
use Workerman\Worker;

// Create a worker instance
$worker = new Worker('websocket://0.0.0.0:12345');

// Configure with your own logger and cache implementation
$logger = new YourPsrLogger();
$cache = new YourPsrCache();

$worker->onConnect = function (ConnectionInterface $connection) use ($logger, $cache) {
    // Create a user and associate it with the connection
    $user = new User(
        $logger,
        $cache,
        123, // User ID
        'password123', // Password (if needed)
        1024 // Speed limit in bytes/second (if needed)
    );

    ConnectionManager::setUser($connection, $user);
};

$worker->onMessage = function (ConnectionInterface $connection, $data) {
    // Get user associated with this connection
    $user = ConnectionManager::getUser($connection);

    if ($user) {
        // Track data usage
        $bytes = strlen($data);
        $user->incrUploadSize($bytes);

        // Check if user exceeds speed limit
        $speedLimit = $user->getSpeedLimit();
        if ($speedLimit > 0 && $user->getUploadSize() > $speedLimit) {
            // Handle speed limit exceeded
        }
    }
};

$worker->onClose = function (ConnectionInterface $connection) {
    // No need to clean up, WeakMap handles this automatically
};

Worker::runAll();

// Constructor
public function __construct(
    private readonly LoggerInterface $logger,
    private readonly CacheInterface $cache,
    private readonly int $id,
    private readonly string $password = '',
    private readonly int $speedLimit = 0,
)

// Methods
public function getId(): int
public function getPassword(): string
public function getSpeedLimit(): int

// Upload statistics
public function incrUploadSize(int $flowSize): int
public function getUploadSize(): int
public function popUploadStat(): int

// Download statistics
public function incrDownloadSize(int $flowSize): int
public function getDownloadSize(): int
public function popDownloadStat(): int

// Static methods
public static function init(): void
public static function getUser(ConnectionInterface $connection): ?User
public static function setUser(ConnectionInterface $connection, User $user): void