-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathexample.php
More file actions
547 lines (479 loc) Β· 18.3 KB
/
example.php
File metadata and controls
547 lines (479 loc) Β· 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
<?php
// PostHog PHP library example
//
// This script demonstrates various PostHog PHP SDK capabilities including:
// - Basic event capture and user identification
// - Feature flag local evaluation
// - Feature flag dependencies
// - Context management and tagging
//
// Setup:
// 1. Copy .env.example to .env and fill in your PostHog credentials
// 2. Run this script and choose from the interactive menu
require_once __DIR__ . '/vendor/autoload.php';
use PostHog\PostHog;
function loadEnvFile()
{
$envPath = __DIR__ . '/.env';
if (file_exists($envPath)) {
$lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
if ($line && ($line[0] !== '#') && strpos($line, '=') !== false) {
list($key, $value) = explode('=', $line, 2);
$_ENV[trim($key)] = trim($value);
putenv(trim($key) . '=' . trim($value));
}
}
}
}
// Load .env file if it exists
loadEnvFile();
// Get configuration
$projectKey = $_ENV['POSTHOG_PROJECT_API_KEY'] ?? getenv('POSTHOG_PROJECT_API_KEY') ?: '';
$personalApiKey = $_ENV['POSTHOG_PERSONAL_API_KEY'] ?? getenv('POSTHOG_PERSONAL_API_KEY') ?: '';
$host = $_ENV['POSTHOG_HOST'] ?? getenv('POSTHOG_HOST') ?: 'https://app.posthog.com';
// Check if credentials are provided
if (!$projectKey || !$personalApiKey) {
echo "β Missing PostHog credentials!\n";
echo " Please set POSTHOG_PROJECT_API_KEY and POSTHOG_PERSONAL_API_KEY environment variables\n";
echo " or copy .env.example to .env and fill in your values\n";
exit(1);
}
// Test authentication before proceeding
echo "π Testing PostHog authentication...\n";
try {
// Configure PostHog with credentials
PostHog::init(
$projectKey,
[
'host' => $host,
'debug' => false,
'ssl' => !(substr($host, 0, 7) === 'http://') // Use SSL unless explicitly http://
],
null,
$personalApiKey
);
// Test by attempting to get feature flags (this validates both keys)
$testFlags = PostHog::getAllFlags("test_user", [], [], [], true);
// If we get here without exception, credentials work
echo "β
Authentication successful!\n";
echo " Project API Key: " . substr($projectKey, 0, 9) . "...\n";
echo " Personal API Key: [REDACTED]\n";
echo " Host: $host\n\n\n";
} catch (Exception $e) {
echo "β Authentication failed!\n";
echo " Error: " . $e->getMessage() . "\n";
echo "\n Please check your credentials:\n";
echo " - POSTHOG_PROJECT_API_KEY: Project API key from PostHog settings\n";
echo " - POSTHOG_PERSONAL_API_KEY: Personal API key (required for local evaluation)\n";
echo " - POSTHOG_HOST: Your PostHog instance URL\n";
exit(1);
}
// Display menu and get user choice
echo "π PostHog PHP SDK Demo - Choose an example to run:\n\n";
echo "1. Identify and capture examples\n";
echo "2. Feature flag local evaluation examples\n";
echo "3. Feature flag dependencies examples\n";
echo "4. Context management and tagging examples\n";
echo "5. ETag polling examples (for local evaluation)\n";
echo "6. Run all examples\n";
echo "7. Exit\n";
$choice = trim(readline("\nEnter your choice (1-7): "));
function identifyAndCaptureExamples()
{
echo "\n" . str_repeat("=", 60) . "\n";
echo "IDENTIFY AND CAPTURE EXAMPLES\n";
echo str_repeat("=", 60) . "\n";
// Enable debug for this section
PostHog::init(
$_ENV['POSTHOG_PROJECT_API_KEY'],
[
'host' => $_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com',
'debug' => true,
'ssl' => !str_starts_with($_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com', 'http://')
],
null,
$_ENV['POSTHOG_PERSONAL_API_KEY']
);
// Capture an event
echo "π Capturing events...\n";
PostHog::capture([
'distinctId' => 'distinct_id',
'event' => 'event',
'properties' => [
'property1' => 'value',
'property2' => 'value',
],
'send_feature_flags' => true
]);
// Alias a previous distinct id with a new one
echo "π Creating alias...\n";
PostHog::alias([
'distinctId' => 'distinct_id',
'alias' => 'new_distinct_id'
]);
PostHog::capture([
'distinctId' => 'new_distinct_id',
'event' => 'event2',
'properties' => [
'property1' => 'value',
'property2' => 'value',
]
]);
PostHog::capture([
'distinctId' => 'new_distinct_id',
'event' => 'event-with-groups',
'properties' => [
'property1' => 'value',
'property2' => 'value',
],
'groups' => ['company' => 'id:5']
]);
// Add properties to the person
echo "π€ Identifying user...\n";
PostHog::identify([
'distinctId' => 'new_distinct_id',
'properties' => ['email' => 'something@something.com']
]);
echo "β
Identify and capture examples completed!\n";
}
function featureFlagExamples()
{
echo "\n" . str_repeat("=", 60) . "\n";
echo "FEATURE FLAG LOCAL EVALUATION EXAMPLES\n";
echo str_repeat("=", 60) . "\n";
// Disable debug for cleaner output
PostHog::init(
$_ENV['POSTHOG_PROJECT_API_KEY'],
[
'host' => $_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com',
'debug' => false,
'ssl' => !str_starts_with($_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com', 'http://')
],
null,
$_ENV['POSTHOG_PERSONAL_API_KEY']
);
echo "π© Getting individual feature flags...\n";
// Test different users to see different results
$users = ['user_1', 'user_2', 'user_3'];
foreach ($users as $user) {
$flags = PostHog::getAllFlags($user, [], [], [], true);
echo "User $user flags: " . json_encode($flags, JSON_PRETTY_PRINT) . "\n";
// Get a specific flag
if (!empty($flags)) {
$firstFlag = array_key_first($flags);
$flagValue = PostHog::getFeatureFlag($firstFlag, $user, [], [], [], true);
echo "Flag '$firstFlag' for $user: " . ($flagValue ? json_encode($flagValue) : 'false') . "\n";
}
echo "\n";
}
echo "β
Feature flag examples completed!\n";
}
function flagDependencyExamples()
{
echo "\n" . str_repeat("=", 60) . "\n";
echo "FLAG DEPENDENCIES EXAMPLES\n";
echo str_repeat("=", 60) . "\n";
echo "π Testing flag dependencies with local evaluation...\n";
echo " Flag structure: 'test-flag-dependency' depends on 'beta-feature' being enabled\n";
echo "\n";
echo "π Required setup (if 'test-flag-dependency' doesn't exist):\n";
echo " 1. Create feature flag 'beta-feature':\n";
echo " - Condition: email contains '@example.com'\n";
echo " - Rollout: 100%\n";
echo " 2. Create feature flag 'test-flag-dependency':\n";
echo " - Condition: flag 'beta-feature' is enabled\n";
echo " - Rollout: 100%\n";
echo "\n";
// Enable debug for this section
PostHog::init(
$_ENV['POSTHOG_PROJECT_API_KEY'],
[
'host' => $_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com',
'debug' => true,
'ssl' => !str_starts_with($_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com', 'http://')
],
null,
$_ENV['POSTHOG_PERSONAL_API_KEY']
);
// Test @example.com user (should satisfy dependency if flags exist)
$result1 = PostHog::getFeatureFlag(
"test-flag-dependency",
"example_user",
[],
["email" => "user@example.com"],
[],
true // only_evaluate_locally
);
echo "β
@example.com user (test-flag-dependency): " . json_encode($result1) . "\n";
// Test non-example.com user (dependency should not be satisfied)
$result2 = PostHog::getFeatureFlag(
"test-flag-dependency",
"regular_user",
[],
["email" => "user@other.com"],
[],
true
);
echo "β Regular user (test-flag-dependency): " . json_encode($result2) . "\n";
// Test beta-feature directly for comparison
$beta1 = PostHog::getFeatureFlag(
"beta-feature",
"example_user",
[],
["email" => "user@example.com"],
[],
true
);
$beta2 = PostHog::getFeatureFlag(
"beta-feature",
"regular_user",
[],
["email" => "user@other.com"],
[],
true
);
echo "π Beta feature comparison - @example.com: " . json_encode($beta1) . ", regular: " . json_encode($beta2) . "\n";
echo "\nπ― Results Summary:\n";
echo " - Flag dependencies evaluated locally: " . ($result1 != $result2 ? "β
YES" : "β NO") . "\n";
echo " - Zero API calls needed: β
YES (all evaluated locally)\n";
echo " - PHP SDK supports flag dependencies: β
YES\n";
echo "\n" . str_repeat("-", 60) . "\n";
echo "PRODUCTION-STYLE MULTIVARIATE DEPENDENCY CHAIN\n";
echo str_repeat("-", 60) . "\n";
echo "π Testing complex multivariate flag dependencies...\n";
echo " Structure: multivariate-root-flag -> multivariate-intermediate-flag -> multivariate-leaf-flag\n";
echo "\n";
echo "π Required setup (if flags don't exist):\n";
echo " 1. Create 'multivariate-leaf-flag' with fruit variants (pineapple, mango, papaya, kiwi)\n";
echo " - pineapple: email = 'pineapple@example.com'\n";
echo " - mango: email = 'mango@example.com'\n";
echo " 2. Create 'multivariate-intermediate-flag' with color variants (blue, red)\n";
echo " - blue: depends on multivariate-leaf-flag = 'pineapple'\n";
echo " - red: depends on multivariate-leaf-flag = 'mango'\n";
echo " 3. Create 'multivariate-root-flag' with show variants (breaking-bad, the-wire)\n";
echo " - breaking-bad: depends on multivariate-intermediate-flag = 'blue'\n";
echo " - the-wire: depends on multivariate-intermediate-flag = 'red'\n";
echo "\n";
// Test pineapple -> blue -> breaking-bad chain
$dependentResult3 = PostHog::getFeatureFlag(
"multivariate-root-flag",
"regular_user",
[],
["email" => "pineapple@example.com"],
[],
true
);
if ($dependentResult3 !== "breaking-bad") {
echo " β Something went wrong evaluating 'multivariate-root-flag' with pineapple@example.com. Expected 'breaking-bad', got '" . json_encode($dependentResult3) . "'\n";
} else {
echo "β
'multivariate-root-flag' with email pineapple@example.com succeeded\n";
}
// Test mango -> red -> the-wire chain
$dependentResult4 = PostHog::getFeatureFlag(
"multivariate-root-flag",
"regular_user",
[],
["email" => "mango@example.com"],
[],
true
);
if ($dependentResult4 !== "the-wire") {
echo " β Something went wrong evaluating multivariate-root-flag with mango@example.com. Expected 'the-wire', got '" . json_encode($dependentResult4) . "'\n";
} else {
echo "β
'multivariate-root-flag' with email mango@example.com succeeded\n";
}
// Show the complete chain evaluation
echo "\nπ Complete dependency chain evaluation:\n";
$scenarios = [
["email" => "pineapple@example.com", "expected" => ["pineapple", "blue", "breaking-bad"]],
["email" => "mango@example.com", "expected" => ["mango", "red", "the-wire"]]
];
foreach ($scenarios as $scenario) {
$email = $scenario["email"];
$expectedChain = $scenario["expected"];
$leaf = PostHog::getFeatureFlag(
"multivariate-leaf-flag",
"regular_user",
[],
["email" => $email],
[],
true
);
$intermediate = PostHog::getFeatureFlag(
"multivariate-intermediate-flag",
"regular_user",
[],
["email" => $email],
[],
true
);
$root = PostHog::getFeatureFlag(
"multivariate-root-flag",
"regular_user",
[],
["email" => $email],
[],
true
);
$actualChain = [$leaf, $intermediate, $root];
$chainSuccess = $actualChain === $expectedChain;
echo " π§ $email:\n";
echo " Expected: " . implode(" -> ", $expectedChain) . "\n";
echo " Actual: " . implode(" -> ", array_map('strval', $actualChain)) . "\n";
echo " Status: " . ($chainSuccess ? "β
SUCCESS" : "β FAILED") . "\n";
}
echo "\nπ― Multivariate Chain Summary:\n";
echo " - Complex dependency chains: β
SUPPORTED\n";
echo " - Multivariate flag dependencies: β
SUPPORTED\n";
echo " - Local evaluation of chains: β
WORKING\n";
}
function contextManagementExamples()
{
echo "\n" . str_repeat("=", 60) . "\n";
echo "CONTEXT MANAGEMENT AND TAGGING EXAMPLES\n";
echo str_repeat("=", 60) . "\n";
// Enable debug for this section
PostHog::init(
$_ENV['POSTHOG_PROJECT_API_KEY'],
[
'host' => $_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com',
'debug' => true,
'ssl' => !str_starts_with($_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com', 'http://')
],
null,
$_ENV['POSTHOG_PERSONAL_API_KEY']
);
echo "π·οΈ Testing groups and properties...\n";
// Capture event with groups
PostHog::capture([
'distinctId' => 'group_user_1',
'event' => 'group_event',
'properties' => [
'plan' => 'enterprise',
'feature_used' => 'advanced_analytics'
],
'groups' => [
'company' => 'acme_corp',
'team' => 'engineering'
]
]);
// Test feature flags with group properties
echo "π© Testing flags with group context...\n";
$flagValue = PostHog::getFeatureFlag(
"enterprise_features",
"group_user_1",
['company' => 'acme_corp'],
['plan' => 'enterprise'],
['company' => ['name' => 'Acme Corp', 'employees' => 100]]
);
echo "Enterprise features flag: " . ($flagValue ? json_encode($flagValue) : 'false') . "\n";
echo "β
Context management examples completed!\n";
}
function etagPollingExamples()
{
echo "\n" . str_repeat("=", 60) . "\n";
echo "ETAG POLLING EXAMPLES\n";
echo str_repeat("=", 60) . "\n";
echo "This example demonstrates ETag-based caching for feature flags.\n";
echo "ETag support reduces bandwidth by skipping full payload transfers\n";
echo "when flags haven't changed (304 Not Modified response).\n\n";
// Re-initialize with debug enabled
PostHog::init(
$_ENV['POSTHOG_PROJECT_API_KEY'],
[
'host' => $_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com',
'debug' => true,
'ssl' => !str_starts_with($_ENV['POSTHOG_HOST'] ?? 'https://app.posthog.com', 'http://')
],
null,
$_ENV['POSTHOG_PERSONAL_API_KEY']
);
$client = PostHog::getClient();
// Initial load - should get full response with ETag
echo "π₯ Initial flag load (expecting full response with ETag)...\n";
$client->loadFlags();
$initialEtag = $client->getFlagsEtag();
$flagCount = count($client->featureFlags);
if ($initialEtag) {
echo " β
Received ETag: " . substr($initialEtag, 0, 30) . "...\n";
} else {
echo " β οΈ No ETag received (server may not support ETag caching)\n";
}
echo " π Loaded $flagCount feature flag(s)\n\n";
// Second load - should get 304 Not Modified if flags haven't changed
echo "π₯ Second flag load (expecting 304 Not Modified if unchanged)...\n";
$client->loadFlags();
$secondEtag = $client->getFlagsEtag();
$secondFlagCount = count($client->featureFlags);
echo " π Flag count: $secondFlagCount (should match initial: $flagCount)\n";
if ($secondEtag === $initialEtag && $initialEtag !== null) {
echo " β
ETag unchanged - server likely returned 304 Not Modified\n";
} elseif ($secondEtag !== null) {
echo " π ETag changed: " . substr($secondEtag, 0, 30) . "...\n";
echo " (flags may have been updated on the server)\n";
}
echo "\n";
// Continuous polling - runs until Ctrl+C
echo "π Starting continuous polling (every 5 seconds)...\n";
echo " Press Ctrl+C to stop.\n";
echo " Try changing feature flags in PostHog to see ETag changes!\n\n";
$iteration = 1;
while (true) {
$timestamp = date('H:i:s');
echo " [$timestamp] Poll #$iteration: ";
$beforeEtag = $client->getFlagsEtag();
$client->loadFlags();
$afterEtag = $client->getFlagsEtag();
$currentFlagCount = count($client->featureFlags);
if ($beforeEtag === $afterEtag && $beforeEtag !== null) {
echo "No change (304 Not Modified) - $currentFlagCount flag(s)\n";
} else {
echo "π Flags updated! New ETag: " . ($afterEtag ? substr($afterEtag, 0, 20) . "..." : "none") . " - $currentFlagCount flag(s)\n";
}
$iteration++;
sleep(5);
}
}
function runAllExamples()
{
identifyAndCaptureExamples();
echo "\n" . str_repeat("-", 60) . "\n";
featureFlagExamples();
echo "\n" . str_repeat("-", 60) . "\n";
flagDependencyExamples();
echo "\n" . str_repeat("-", 60) . "\n";
contextManagementExamples();
echo "\nπ All examples completed!\n";
echo " (ETag polling skipped - run separately with option 5)\n";
}
// Handle user choice
switch ($choice) {
case '1':
identifyAndCaptureExamples();
break;
case '2':
featureFlagExamples();
break;
case '3':
flagDependencyExamples();
break;
case '4':
contextManagementExamples();
break;
case '5':
etagPollingExamples();
break;
case '6':
runAllExamples();
break;
case '7':
echo "π Goodbye!\n";
exit(0);
default:
echo "β Invalid choice. Please run the script again and choose 1-7.\n";
exit(1);
}
echo "\nπ‘ Tip: Check your PostHog dashboard to see the captured events and user data!\n";
echo "π For more examples and documentation, visit: https://posthog.com/docs/integrations/php-integration\n";