|
| 1 | +--- |
| 2 | +title: "Getting started: Pub/Sub in PHP" |
| 3 | +meta_description: "A getting started guide for Ably Pub/Sub PHP that steps through some of the key features using PHP." |
| 4 | +meta_keywords: "Pub/Sub PHP, PHP PubSub, Ably PHP SDK, publish PHP, Ably Pub/Sub guide, PHP realtime communication, Ably tutorial PHP, PHP message history, presence API PHP, Ably Pub/Sub example, realtime Pub/Sub PHP, publish message PHP, Ably CLI Pub/Sub" |
| 5 | +languages: |
| 6 | + - PHP |
| 7 | +--- |
| 8 | + |
| 9 | +This guide will get you started with Ably Pub/Sub in PHP. |
| 10 | + |
| 11 | +It will take you through the following steps: |
| 12 | + |
| 13 | +* Create a client and establish a connection to Ably with the Rest SDK. |
| 14 | +* Generate a Token and TokenRequest. |
| 15 | +* Publish a message to the channel with your client for subscribers to receive. |
| 16 | +* Retrieve the presence set of the channel. |
| 17 | +* Retrieve the messages you sent in the guide from history. |
| 18 | + |
| 19 | +h2(#prerequisites). Prerequisites |
| 20 | + |
| 21 | +* "Sign up":https://ably.com/signup for an Ably account. |
| 22 | +** Create a new app, and create your first API key. |
| 23 | +** Your API key will need the @publish@, @presence@, and @history@ capabilities. |
| 24 | + |
| 25 | +* Install the Ably CLI: |
| 26 | + |
| 27 | +```[sh] |
| 28 | +npm install -g @ably/cli |
| 29 | +``` |
| 30 | + |
| 31 | +* Run the following to log in to your Ably account and set the default app and API key: |
| 32 | + |
| 33 | +```[sh] |
| 34 | +ably login |
| 35 | + |
| 36 | +ably apps switch |
| 37 | +ably auth keys switch |
| 38 | +``` |
| 39 | + |
| 40 | +* Install "PHP":https://www.php.net/downloads.php version 7.2 or greater. |
| 41 | +* Create a new project and install the Ably Pub/Sub PHP SDK: |
| 42 | + |
| 43 | +```[sh] |
| 44 | +# Create a new directory for your project |
| 45 | +mkdir ably-php-quickstart |
| 46 | +cd ably-php-quickstart |
| 47 | + |
| 48 | +# Initialize Composer (if you don't have a composer.json yet) |
| 49 | +composer init |
| 50 | + |
| 51 | +# Install the Ably PHP SDK |
| 52 | +composer require ably/ably-php |
| 53 | +``` |
| 54 | + |
| 55 | +<aside data-type='note'> |
| 56 | +<p>The code examples in this guide include a demo API key. If you wish to interact with the Ably CLI and view outputs within your Ably account, ensure that you replace them with your own API key.</p> |
| 57 | +</aside> |
| 58 | + |
| 59 | + |
| 60 | +h2(#step-1). Step 1: Configure the Ably Rest SDK client |
| 61 | + |
| 62 | +Clients establish a connection with Ably when they instantiate a REST SDK instance. This enables them to send messages across channels. |
| 63 | + |
| 64 | +* Create a @get_started.php@ file in your project and add the following code to instantiate the SDK and make requests to Ably. At the minimum you need to provide an authentication mechanism. Use an API key for simplicity, but you should use token authentication in a production app. A @client_id@ ensures the client is identified, which, with the PHP Rest SDK is identifying the name of the user sending a message: |
| 65 | + |
| 66 | +```[php] |
| 67 | +<?php |
| 68 | + |
| 69 | +require 'vendor/autoload.php'; |
| 70 | + |
| 71 | +use Ably\AblyRest; |
| 72 | + |
| 73 | +$ably = new AblyRest(['key' => '{{API_KEY}}', 'clientId' => 'my-first-client']); |
| 74 | +``` |
| 75 | + |
| 76 | +h2(#step-2). Step 2: Generate a JWT |
| 77 | + |
| 78 | +The Ably PHP SDK provides token authentication for secure client connections. Authentication with a JWT is recommended over using API keys directly in production because they can be scoped to specific capabilities and have expiration times. This is essential when authenticating frontend clients where embedding API keys would expose them publicly. As this is a PHP getting started guide, the API key would be considered securely stored as it is on the server side. |
| 79 | + |
| 80 | +This section will show you how to build a JWT with the Ably API credentials embedded, which you can then return to your frontend clients, for example from an API endpoint. |
| 81 | + |
| 82 | +First install the Firebase JWT library, which is used to create and verify JSON Web Tokens (JWTs): |
| 83 | + |
| 84 | +```[bash] |
| 85 | +composer require firebase/php-jwt |
| 86 | +``` |
| 87 | + |
| 88 | +Import the necessary classes at the top of your @get_started.php@ file: |
| 89 | + |
| 90 | +```[php] |
| 91 | +use Firebase\JWT\JWT; |
| 92 | +use Firebase\JWT\Key; |
| 93 | +``` |
| 94 | + |
| 95 | +Then create a new JWT with the following code: |
| 96 | + |
| 97 | +```[php] |
| 98 | +$currentTime = time(); |
| 99 | +$payload = [ |
| 100 | + 'iat' => $currentTime, |
| 101 | + 'exp' => $currentTime + 3600, |
| 102 | + 'x-ably-capability' => '{"*":["*"]}' |
| 103 | +]; |
| 104 | + |
| 105 | +$apiKeyCredentials = explode(':', '{{API_KEY}}'); |
| 106 | +$jwt = JWT::encode( |
| 107 | + $payload, |
| 108 | + $apiKeyCredentials[1], |
| 109 | + 'HS256', |
| 110 | + $apiKeyCredentials[0] |
| 111 | +); |
| 112 | + |
| 113 | +echo $jwt; |
| 114 | +``` |
| 115 | + |
| 116 | +h2(#step-3). Step 3: Publish a message to a channel |
| 117 | + |
| 118 | +Messages contain the data that a client is communicating, such as a short 'hello' from a colleague, or a financial update being broadcast to subscribers from a server. Ably uses channels to separate messages into different topics, so that clients only ever receive messages on the channels they are subscribed to. The PHP SDK and Rest API can only publish messages to channels and cannot subscribe to them. To subscribe to channels, for this guide, you will make use of the Ably CLI. |
| 119 | + |
| 120 | +* Use the Ably CLI to subscribe to a channel a message to your first channel. The message will be received by the client you've subscribed to the channel, and be logged to the console. |
| 121 | + |
| 122 | +```[sh] |
| 123 | +ably channels subscribe my-first-channel |
| 124 | +``` |
| 125 | + |
| 126 | +* Add the following lines to the bottom of your @get_started@ file to create a channel instance and register a listener to publish a message to the channel. Then run it with @php get_started.php@: |
| 127 | + |
| 128 | +```[php] |
| 129 | +$channel = $ably->channel('my-first-channel'); |
| 130 | +$channel->publish('myEvent', 'Hello!'); |
| 131 | +``` |
| 132 | + |
| 133 | +If you check the console where you subscribed to the channel with the Ably CLI, you should see the message appear. |
| 134 | + |
| 135 | +h2(#step-4). Step 4: Presence |
| 136 | + |
| 137 | +Presence enables clients to be aware of one another if they are present on the same channel. You can then show clients who else is online, provide a custom status update for each, and notify the channel when someone goes offline. With the PHP SDK you can retrieve the presence set but cannot enter it. This means you can see who is present on a channel, but you cannot announce your own presence from a PHP client. |
| 138 | + |
| 139 | +* Have a client join the presence set using the Ably CLI: |
| 140 | + |
| 141 | +```[sh] |
| 142 | +ably channels presence enter my-first-channel --client-id "my-cli" --data '{"status":"learning about Ably!"}' |
| 143 | +``` |
| 144 | + |
| 145 | +* Add the following lines to your @get_started@ function to retrieve the list of members in the presence set. Then run it with @php get_started.php@: |
| 146 | + |
| 147 | +```[php] |
| 148 | +$membersPage = $channel->presence->get(); // Returns a PaginatedResult |
| 149 | +$memberIds = array_map(function($member) { |
| 150 | + return $member->clientId; |
| 151 | +}, $membersPage->items); |
| 152 | +echo "Members in presence set: " . implode(', ', $memberIds) . "\n"; |
| 153 | +``` |
| 154 | + |
| 155 | +h2(#step-5). Step 5: Retrieve message history |
| 156 | + |
| 157 | +You can retrieve previously sent messages using the history feature. Ably stores all messages for 2 minutes by default in the event a client experiences network connectivity issues. This can be extended for longer if required. |
| 158 | + |
| 159 | +If more than 2 minutes has passed since you published a regular message (excluding the presence events), then you can publish some more before trying out history. You can use the Pub/Sub SDK, Ably CLI or the dev console to do this. |
| 160 | + |
| 161 | +For example, using the Ably CLI to publish 5 messages: |
| 162 | + |
| 163 | +```[sh] |
| 164 | +ably channels publish --count 5 my-first-channel "Message number {{.Count}}" |
| 165 | +``` |
| 166 | + |
| 167 | +* Add the following lines to your @get_started@ function to retrieve any messages that were recently published to the channel. Then run it with @php get_started.php@: |
| 168 | + |
| 169 | +```[php] |
| 170 | +$history = $channel->history(); |
| 171 | + |
| 172 | +echo "\nMessage History:\n"; |
| 173 | +echo str_repeat("-", 50) . "\n"; |
| 174 | + |
| 175 | +foreach ($history->items as $index => $message) { |
| 176 | + echo " * " . ($message->data ?? 'null') . "\n"; |
| 177 | +} |
| 178 | +``` |
| 179 | + |
| 180 | +The output will look similar to the following: |
| 181 | + |
| 182 | +```[json] |
| 183 | +[ |
| 184 | + 'Message number 5', |
| 185 | + 'Message number 4', |
| 186 | + 'Message number 3', |
| 187 | + 'Message number 2', |
| 188 | + 'Message number 1' |
| 189 | +] |
| 190 | +``` |
| 191 | + |
| 192 | +h2(#next). Next steps |
| 193 | + |
| 194 | +Continue to explore the documentation with PHP as the selected language: |
| 195 | + |
| 196 | +Read more about the concepts covered in this guide: |
| 197 | + |
| 198 | +* Revisit the basics of "Pub/Sub":/docs/pub-sub?lang=php |
| 199 | +* Explore more "advanced":/docs/pub-sub/advanced?lang=php Pub/Sub concepts |
| 200 | +* Read more about how to use "presence":/docs/presence-occupancy/presence?lang=php in your apps |
| 201 | +* Fetch message "history":/docs/storage-history/history?lang=php in your apps |
| 202 | + |
| 203 | +You can also explore the Ably CLI further, or visit the Pub/Sub "API references":/docs/api/rest-sdk?lang=php. |
0 commit comments