phpcent

repository·master·Indexed 41 days ago

https://github.com/centrifugal/phpcent

A PHP library for communicating with the Centrifugo HTTP API. It enables developers to publish messages, broadcast data to multiple channels, manage user subscriptions and connections, retrieve channel presence and history, and generate JWT tokens for client connections and subscriptions. Supports Centrifugo v5 (via phpcent v6.x), v4 (via v5.x), and v3 (via v4.x).

Tokens
2.7K
Snippets
13
Records
14
Agent score
2%

What's inside phpcent

  1. Install phpcent via Composer

    master

    To use phpcent with Centrifugo v5, install the library using Composer. Note that version compatibility is important: use phpcent v6.x for Centrifugo v5, v5.x for Centrifugo v4, and v4.x for Centrifugo v3.

    composer require centrifugal/phpcent:~6.0
  2. Initialize the Centrifugo Client

    master

    To communicate with the Centrifugo HTTP API, instantiate the phpcent\Client class. You must provide the API endpoint URL, the API key, and the secret key used for signing tokens.

    Methods available for configuration:

    • setApiKey(string $key): Sets the API key.
    • setSecret(string $secret): Sets the secret key.
    • setUseAssoc(bool $useAssoc): If true, JSON responses will be decoded as associative arrays instead of objects.
    • setSafety(bool $safety): Enables or disables SSL verification. Defaults to true (safe).
    • setTimeoutOption(int $timeout): Sets the cURL timeout.
    • setConnectTimeoutOption(int $timeout): Sets the cURL connection timeout.
    • forceIpResolveV4(): Forces DNS to resolve only IPv4 addresses.
    use phpcent\Client;
    
    $client = new Client('http://localhost:8000/api', 'YOUR_API_KEY', 'YOUR_SECRET');
    $client->setUseAssoc(true);
  3. Generate Connection and Subscription Tokens (JWT)

    master

    The phpcent client can generate JSON Web Tokens (JWT) required for client connections and channel subscriptions. You must first set the Centrifugo secret key using setSecret().

    // Generate a connection token for a user
    $token = $client->setSecret("Centrifugo secret key")->generateConnectionToken($userId);
    
    // Generate a connection token with a specific expiration (e.g., 5 minutes from now)
    $token = $client->setSecret("Centrifugo secret key")->generateConnectionToken($userId, time() + 5*60);
    
    // Generate a channel subscription token
    $token = $client->setSecret("Centrifugo secret key")->generateSubscriptionToken($userId, $channel);
    
    // Generate a channel subscription token with an expiration (e.g., 30 minutes)
    $token = $client->setSecret("Centrifugo secret key")->generateSubscriptionToken($userId, $channel, time() + 30*60);
  4. Configure Client timeouts and response format

    master

    You can adjust connection and request timeouts, and change how JSON responses are decoded.

    // Set connection timeout (0 = never)
    $client->setConnectTimeoutOption(0);
    
    // Set request timeout in seconds
    $client->setTimeoutOption(2);
    
    // Decode JSON responses as associative arrays instead of objects
    $client->setUseAssoc(true);
  5. Initialize the phpcent Client

    master

    You can initialize the \phpcent\Client by providing the API endpoint in the constructor. You can also provide the API key and the secret key directly in the constructor to simplify setup.

    // Basic initialization
    $client = new \phpcent\Client("http://localhost:8000/api");
    $client->setApiKey("Centrifugo API key");
    
    // Initialization with API key and secret key in constructor
    $client = new \phpcent\Client("http://localhost:8000/api", "<API key>", "<secret key>");
  6. Use phpcent API methods

    master

    The Client class provides several methods to interact with the Centrifugo HTTP API. Most methods return a response object.

    $response = $client->publish($channel, $data);
    $response = $client->broadcast($channels, $data);
    $response = $client->subscribe($channel, $userId);
    $response = $client->unsubscribe($channel, $userId);
    $response = $client->disconnect($userId);
    $response = $client->presence($channel);
    $response = $client->presenceStats($channel);
    $response = $client->history($channel);
    $response = $client->historyRemove($channel);
    $response = $client->channels();
    $response = $client->info();
    $response = $client->batch($data);
  7. Configure SSL and Certificates

    master

    If your Centrifugo server uses a self-signed certificate or an invalid SSL certificate, you can configure the client to handle it. If you use a custom certificate, ensure it matches the hostname used in the Client address.

    // Disable SSL safety (for invalid certificates)
    $client->setSafety(false);
    
    // Use a self-signed certificate safely
    $client = new \phpcent\Client("https://localhost:8000/api");
    $client->setCert("/path/to/certificate.pem");
    $client->setCAPath("/ca/path"); // Optional
  8. Broadcast data to multiple channels

    master

    Use the broadcast method to send the same data payload to an array of channels simultaneously.

    Parameters:

    • array $channels: An array of channel names.
    • array $data: The payload to send.
    • bool $skipHistory (optional): Whether to skip history.
    • array $tags (optional): Map of string key/value tags.
    • string $idempotencyKey (optional): Key to prevent duplicate processing.
    • bool $delta (optional): Enable delta compression.
    • int $version (optional): Publication version (0 means not set).
    • string $versionEpoch (optional): Publication version epoch.
    $client->broadcast(['room1', 'room2'], ['event' => 'update']);
  9. Generate JWT Subscription Tokens

    master

    The generateSubscriptionToken method creates a JWT for authorizing a specific channel subscription. It uses the HS256 algorithm and the client's configured secret.

    Parameters:

    • string $userId: The unique ID of the user.
    • string $channel: The specific channel the token is for.
    • int $exp (optional): Unix timestamp for token expiration.
    • array $info (optional): Additional info claims.
    $token = $client->generateSubscriptionToken('user_1', 'chat:room1', time() + 3600, ['premium' => true]);
  10. Retrieve channel presence and history

    master

    Use these methods to inspect channel state:

    • presence(string $channel): Returns presence information for a channel.
    • presenceStats(string $channel): Returns presence statistics for a channel.
    • history(string $channel, int $limit = 0, array $since = [], bool $reverse = false): Retrieves channel history.
    • historyRemove(string $channel): Removes the history for a specific channel.
    • channels(string $pattern = ''): Returns all active channels, optionally filtered by a pattern.
  11. Generate JWT Connection Tokens

    master

    The generateConnectionToken method creates a JWT for authenticating a client connection to Centrifugo. It uses the HS256 algorithm and the client's configured secret.

    Parameters:

    • string $userId: The unique ID of the user.
    • int $exp (optional): Unix timestamp for token expiration.
    • array $info (optional): Additional info claims.
    • array $channels (optional): List of channels the user is allowed to connect to.
    • array $meta (optional): Metadata claims.
    $token = $client->generateConnectionToken('user_1', time() + 3600, ['role' => 'admin'], ['news', 'updates']);