-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdk-connection-php.php
More file actions
87 lines (75 loc) · 2.5 KB
/
sdk-connection-php.php
File metadata and controls
87 lines (75 loc) · 2.5 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
<?php
/**
* Couchbase SDK connection singleton — PHP
* Copy and adapt for your application.
*
* Dependencies:
* composer require couchbase/couchbase
*/
use Couchbase\ClusterOptions;
use Couchbase\Cluster;
use Couchbase\Collection;
use Couchbase\Exception\CouchbaseException;
// --- Configuration ---
define('CB_HOST', 'localhost'); // or 'cb.xxxxx.cloud.couchbase.com' for Capella
define('CB_USER', 'app-service-user');
define('CB_PASSWORD', 'AppSecret123!');
define('CB_BUCKET', 'myapp');
define('CB_SCOPE', '_default');
define('CB_COLLECTION', '_default');
// Use 'couchbases://' for TLS (required for Capella, recommended for production)
define('CB_SCHEME', 'couchbase');
class CouchbaseConnection
{
private static ?Cluster $cluster = null;
private static ?Collection $collection = null;
/**
* Returns the singleton Collection, initializing the cluster on first call.
*/
public static function getCollection(): Collection
{
if (self::$collection !== null) {
return self::$collection;
}
$options = new ClusterOptions();
$options->credentials(CB_USER, CB_PASSWORD);
$options->connectTimeout(10_000); // ms
$options->kvTimeout(2_500); // ms
$options->queryTimeout(75_000); // ms
$options->searchTimeout(75_000); // ms
self::$cluster = new Cluster(CB_SCHEME . '://' . CB_HOST, $options);
self::$collection = self::$cluster
->bucket(CB_BUCKET)
->scope(CB_SCOPE)
->collection(CB_COLLECTION);
return self::$collection;
}
/**
* Returns the singleton Cluster (needed for queries and transactions).
*/
public static function getCluster(): Cluster
{
self::getCollection(); // ensures cluster is initialized
return self::$cluster;
}
}
// --- Usage example ---
$collection = CouchbaseConnection::getCollection();
$cluster = CouchbaseConnection::getCluster();
// KV upsert
$collection->upsert('doc_1', ['type' => 'example', 'value' => 42]);
// KV get
try {
$result = $collection->get('doc_1');
print_r($result->content());
} catch (CouchbaseException $e) {
echo 'Error: ' . $e->getMessage() . PHP_EOL;
}
// SQL++ query
$result = $cluster->query(
'SELECT * FROM `myapp`._default._default WHERE type = $type LIMIT 5',
\Couchbase\QueryOptions::build()->namedParameters(['type' => 'example'])
);
foreach ($result->rows() as $row) {
print_r($row);
}