Skip to content

Commit 36aafd5

Browse files
committed
Added getting started snippets
1 parent de1c1a3 commit 36aafd5

File tree

3 files changed

+216
-2
lines changed

3 files changed

+216
-2
lines changed
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
<?php
2+
3+
// This file contains code snippets for the Getting Started guide
4+
// Include Composer autoloader (adjust path if needed)
5+
require_once 'vendor/autoload.php';
6+
7+
use PubNub\PNConfiguration;
8+
use PubNub\PubNub;
9+
use PubNub\Callbacks\SubscribeCallback;
10+
use PubNub\Enums\PNStatusCategory;
11+
use PubNub\Exceptions\PubNubServerException;
12+
use PubNub\Exceptions\PubNubException;
13+
14+
// snippet.initialize_pubnub
15+
// Create a new configuration instance
16+
$pnConfiguration = new PNConfiguration();
17+
18+
// Set subscribe key (required)
19+
$pnConfiguration->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo"); // Replace with your subscribe key
20+
21+
// Set publish key (only required if publishing)
22+
$pnConfiguration->setPublishKey(getenv("PUBLISH_KEY") ?? "demo"); // Replace with your publish key
23+
24+
// Set UUID (required to connect)
25+
$pnConfiguration->setUserId("php-sdk-user-" . uniqid());
26+
27+
// Set up cryptography for message encryption (optional)
28+
// $pnConfiguration->setCryptoModule(CryptoModule::aesCbcCryptor("your-cipher-key", true));
29+
30+
// Configure connection timeout in seconds
31+
$pnConfiguration->setConnectTimeout(10);
32+
33+
// Create PubNub instance with the configured settings
34+
$pubnub = new PubNub($pnConfiguration);
35+
// snippet.end
36+
37+
// snippet.event_listeners
38+
class MySubscribeCallback extends SubscribeCallback {
39+
function status($pubnub, $status) {
40+
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
41+
// This event happens when radio / connectivity is lost
42+
echo "Unexpected disconnect - network may be down" . PHP_EOL;
43+
} else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
44+
// Connect event. You can do stuff like publish, and know you'll get it
45+
echo "Connected to PubNub!" . PHP_EOL;
46+
} else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
47+
// Handle message decryption error
48+
echo "Decryption error: " . $status->getException() . PHP_EOL;
49+
}
50+
}
51+
52+
function message($pubnub, $message) {
53+
// Handle new message stored in message.message
54+
echo "Received message: " . json_encode($message->getMessage()) . PHP_EOL;
55+
echo "Publisher: " . $message->getPublisher() . PHP_EOL;
56+
echo "Channel: " . $message->getChannel() . PHP_EOL;
57+
echo "Timetoken: " . $message->getTimetoken() . PHP_EOL;
58+
}
59+
60+
function presence($pubnub, $presence) {
61+
// Handle incoming presence data
62+
echo "Presence event: " . $presence->getEvent() . PHP_EOL;
63+
echo "UUID: " . $presence->getUuid() . PHP_EOL;
64+
echo "Channel: " . $presence->getChannel() . PHP_EOL;
65+
echo "Occupancy: " . $presence->getOccupancy() . PHP_EOL;
66+
}
67+
}
68+
69+
// Add listener
70+
$subscribeCallback = new MySubscribeCallback();
71+
$pubnub->addListener($subscribeCallback);
72+
// snippet.end
73+
74+
// snippet.create_subscription
75+
// Subscribe to a channel
76+
$pubnub->subscribe()
77+
->channels("hello_world")
78+
->withPresence(true) // Optional: subscribe to presence events
79+
->execute();
80+
// snippet.end
81+
82+
// snippet.publish_message
83+
// Assuming $pubnub is already initialized
84+
85+
try {
86+
// Create message data
87+
$messageData = [
88+
"text" => "Hello from PHP SDK!",
89+
"timestamp" => time(),
90+
"sender" => [
91+
"name" => "PHP Publisher",
92+
"id" => $pnConfiguration->getUserId()
93+
]
94+
];
95+
96+
// Publish a message to a channel
97+
$result = $pubnub->publish()
98+
->channel("hello_world") // Channel to publish to
99+
->message($messageData) // Message content
100+
->shouldStore(true) // Store in history
101+
->sync(); // Execute synchronously
102+
103+
// Display success message
104+
echo "Message published successfully!" . PHP_EOL;
105+
echo "Timetoken: " . $result->getTimetoken() . PHP_EOL;
106+
107+
// Convert timetoken to readable date
108+
$timestamp = floor($result->getTimetoken() / 10000000);
109+
$readableDate = date('Y-m-d H:i:s', $timestamp);
110+
echo "Published at: " . $readableDate . PHP_EOL;
111+
112+
// Display published message
113+
echo PHP_EOL . "Published message: " . PHP_EOL;
114+
echo json_encode($messageData, JSON_PRETTY_PRINT) . PHP_EOL;
115+
} catch (PubNubServerException $exception) {
116+
// Handle PubNub server-specific errors
117+
echo "Error publishing message: " . $exception->getMessage() . PHP_EOL;
118+
119+
if (method_exists($exception, 'getServerErrorMessage') && $exception->getServerErrorMessage()) {
120+
echo "Server Error: " . $exception->getServerErrorMessage() . PHP_EOL;
121+
}
122+
123+
if (method_exists($exception, 'getStatusCode') && $exception->getStatusCode()) {
124+
echo "Status Code: " . $exception->getStatusCode() . PHP_EOL;
125+
}
126+
} catch (PubNubException $exception) {
127+
// Handle PubNub-specific errors
128+
echo "PubNub Error: " . $exception->getMessage() . PHP_EOL;
129+
} catch (Exception $exception) {
130+
// Handle general exceptions
131+
echo "Error: " . $exception->getMessage() . PHP_EOL;
132+
}
133+
// snippet.end
134+

examples/basic_usage/publish.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,12 @@
88
use PubNub\Exceptions\PubNubServerException;
99
use PubNub\Exceptions\PubNubException;
1010

11+
// snippet.publish_complete
1112
// Create configuration with demo keys
1213
$pnConfig = new PNConfiguration();
1314
$pnConfig->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo");
1415
$pnConfig->setPublishKey(getenv("PUBLISH_KEY") ?? "demo");
15-
$pnConfig->setUserId("php-publish-demo-user");
16+
$pnConfig->setUserId("php-publisher-demo");
1617

1718
// Initialize PubNub instance
1819
$pubnub = new PubNub($pnConfig);
@@ -30,7 +31,7 @@
3031

3132
// Publish a message to a channel
3233
$result = $pubnub->publish()
33-
->channel("my_channel") // Channel to publish to
34+
->channel("hello_world") // Channel to publish to
3435
->message($messageData) // Message content
3536
->shouldStore(true) // Store in history
3637
->ttl(15) // Time to live (hours)
@@ -68,3 +69,4 @@
6869
// Handle general exceptions
6970
echo "Error: " . $exception->getMessage() . PHP_EOL;
7071
}
72+
// snippet.end

examples/basic_usage/subscribe.php

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
<?php
2+
3+
// Include Composer autoloader (adjust path if needed)
4+
require_once 'vendor/autoload.php';
5+
6+
use PubNub\PubNub;
7+
use PubNub\Enums\PNStatusCategory;
8+
use PubNub\Callbacks\SubscribeCallback;
9+
use PubNub\PNConfiguration;
10+
11+
// snippet.initialize_pubnub
12+
// Create a new configuration instance
13+
$pnConfiguration = new PNConfiguration();
14+
15+
// Set subscribe key (required)
16+
$pnConfiguration->setSubscribeKey(getenv("SUBSCRIBE_KEY") ?? "demo");
17+
18+
// Set publish key (only required if publishing)
19+
$pnConfiguration->setPublishKey(getenv("PUBLISH_KEY") ?? "demo");
20+
21+
// Set UUID (required to connect)
22+
$pnConfiguration->setUserId("php-sdk-subscriber");
23+
24+
// Set up cryptography for message encryption (optional)
25+
// $pnConfiguration->setCryptoModule(CryptoModule::aesCbcCryptor("your-cipher-key", true));
26+
27+
// Configure connection timeout in seconds
28+
$pnConfiguration->setConnectTimeout(10);
29+
30+
// Create PubNub instance with the configured settings
31+
$pubnub = new PubNub($pnConfiguration);
32+
// snippet.end
33+
34+
// snippet.event_listeners
35+
class MySubscribeCallback extends SubscribeCallback {
36+
function status($pubnub, $status) {
37+
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
38+
// This event happens when radio / connectivity is lost
39+
echo "Unexpected disconnect - network may be down" . PHP_EOL;
40+
} else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
41+
// Connect event. You can do stuff like publish, and know you'll get it
42+
echo "Connected to PubNub!" . PHP_EOL;
43+
} else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
44+
// Handle message decryption error
45+
echo "Decryption error: " . $status->getException() . PHP_EOL;
46+
}
47+
}
48+
49+
function message($pubnub, $message) {
50+
// Handle new message stored in message.message
51+
echo "Received message: " . json_encode($message->getMessage()) . PHP_EOL;
52+
echo "Publisher: " . $message->getPublisher() . PHP_EOL;
53+
echo "Channel: " . $message->getChannel() . PHP_EOL;
54+
echo "Timetoken: " . $message->getTimetoken() . PHP_EOL;
55+
}
56+
57+
function presence($pubnub, $presence) {
58+
// Handle incoming presence data
59+
echo "Presence event: " . $presence->getEvent() . PHP_EOL;
60+
echo "UUID: " . $presence->getUuid() . PHP_EOL;
61+
echo "Channel: " . $presence->getChannel() . PHP_EOL;
62+
echo "Occupancy: " . $presence->getOccupancy() . PHP_EOL;
63+
}
64+
}
65+
66+
// Add listener
67+
$subscribeCallback = new MySubscribeCallback();
68+
$pubnub->addListener($subscribeCallback);
69+
// snippet.end
70+
71+
// snippet.create_subscription
72+
// Subscribe to a channel, this will block execution
73+
$pubnub->subscribe()
74+
->channels("hello_world")
75+
->withPresence(true) // Optional: subscribe to presence events
76+
->execute();
77+
// snippet.end
78+

0 commit comments

Comments
 (0)