Skip to content

Commit 0e1b963

Browse files
Added getting started snippets (#126)
* Added getting started snippets * Linter tweaks --------- Co-authored-by: PUBNUB\jakub.grzesiowski <jakub.grzesiowski@pubnub.com>
1 parent de1c1a3 commit 0e1b963

3 files changed

Lines changed: 230 additions & 2 deletions

File tree

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

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

0 commit comments

Comments
 (0)