Install and Start Using the PHP SDK with Couchbase Server
The Couchbase PHP SDK allows you to connect to a Couchbase cluster from PHP. The Couchbase PHP SDK is a native PHP extension and uses the Couchbase high-performance C library to handle communicating to the cluster over Couchbase binary protocols. The Couchbase PHP SDK is compatible with both PHP 5.6 and 7.0.
Installing on Linux
For installation on Linux, install the couchbase-release repository, and then install the libcouchbase packages. The following examples download and install couchbase-release repsitory, a C and C++ compiler, the C SDK development files (libcouchbase-devel [RPM] or libcouchbase-dev [DEB]), PHP development files, and finally the PHP SDK using pecl.
# Only needed during first-time setup:
wget http://packages.couchbase.com/releases/couchbase-release/couchbase-release-1.0-4-amd64.deb
sudo dpkg -i couchbase-release-1.0-4-amd64.deb
# Will install or upgrade packages
sudo apt-get update
sudo apt-get install libcouchbase-dev build-essential php-dev zlib1g-dev
sudo pecl install couchbase
On Ubuntu 14.04 (Trusty), and possibly some other distributions, you will need to substitute for php-dev with php5-dev. To find particular variants of php-dev for your Linux distribution, use the command
|
# Only needed during first-time setup:
wget http://packages.couchbase.com/releases/couchbase-release/couchbase-release-1.0-4-x86_64.rpm
sudo rpm -iv couchbase-release-1.0-4-x86_64.rpm
# Will install or upgrade existing packages
sudo yum install libcouchbase-devel gcc gcc-c++ php-devel zlib-devel
sudo pecl install couchbase
Installation on Mac OS X
As homebrew/php
is no longer available, the current best way to install newer versions of PHP (and one with the necessary permissions) is found at https://php-osx.liip.ch.
Download install.sh
from there or, if you are happy with the script, install in one line (in this example, PHP 7.2) with:
curl -s https://php-osx.liip.ch/install.sh | bash -s 7.2
Once you have PHP installed, then use PECL
to install the Couchbase PHP SDK:
pecl install couchbase
Post Installation - Setting up the php.ini
Once the PHP SDK has been installed, you need to specify that the PHP interpreter should load the Couchbase SDK as an extension. To do this:
-
Locate the location of your php.ini file. This can be done by
php --ini
$ php --ini Configuration File (php.ini) Path: /usr/local/etc/php/7.0 Loaded Configuration File: /usr/local/etc/php/7.0/php.ini Scan for additional .ini files in: /usr/local/etc/php/7.0/conf.d Additional .ini files parsed: (none)
-
Insert the following line in the
php.ini
file; this should be in the[PHP]
section. If you don’t know where that is, simply search for existing commented or uncommentedextension=
entries in the file.Linux and Mac OSextension=couchbase.so
Windowsextension=couchbase.dll
The Couchbase SDK Version 2.2.4 depends on both the JSON and PCS (PHP Code Service) extensions. Releases from 2.0.0 through 2.2.3 and from 2.3.0 forward depend only on the JSON extension. Make sure that the load order is correct. For example, if your distribution has just a single
php.ini
file, just insert the line afterextension=json.so
. If your distribution uses aconf.d
-style, name the file with the Couchbase SDK ini so that it will be alphabetically ordered after the JSON extension.Because the extension depends on the C library (libcouchbase), the shared object libcouchbase.so
orlibcouchbase.dll
has to be accessible by the PHP process when loading the extension. On UNIX-like systems no additional steps are necessary, because the libcouchbase package installs shared objects into a common system location. For Windows though, it must be copied into either into a location from thePATH
for the PHP executable or into a directory with like executables (like apache2, IIS or php.exe). This is controlled by your PHP distribution’s setup, so see its documentation for further information.
Information on new features, fixes, known issues as well as information on how to install older release versions is relnotes-php-sdk.adocl#_version_2_4_7_7_june_2018[in the release notes].
Hello Couchbase
The Hello Couchbase example consists of one PHP file, hello-couchbase.php. The code opens a connection to Couchbase Server, retrieves a document, modifies the document, and stores the updated document in the database. The hello-couchbase.php code is below. Note that to connect to a Couchbase bucket, you must use Couchbase Role-Based Access Control (RBAC). This is fully described in the section Authorization. A username and password for the current user must be specified. Following successful authentication, the bucket is opened.
<?php
$bucketName = "bucket-name";
// Establish username and password for bucket-access
$authenticator = new \Couchbase\PasswordAuthenticator();
$authenticator->username('username')->password('password');
// Connect to Couchbase Server
$cluster = new CouchbaseCluster("couchbase://127.0.0.1");
// Authenticate, then open bucket
$cluster->authenticate($authenticator);
$bucket = $cluster->openBucket($bucketName);
// Store a document
echo "Storing u:king_arthur\n";
$result = $bucket->upsert('u:king_arthur', array(
"email" => "[email protected]",
"interests" => array("African Swallows")
));
var_dump($result);
// Retrieve a document
echo "Getting back u:king_arthur\n";
$result = $bucket->get("u:king_arthur");
var_dump($result->value);
// Replace a document
echo "Replacing u:king_arthur\n";
$doc = $result->value;
array_push($doc->interests, 'PHP 7');
$bucket->replace("u:king_arthur", $doc);
var_dump($result);
echo "Creating primary index\n";
// Before issuing a N1QL Query, ensure that there is
// is actually a primary index.
try {
// Do not override default name; fail if it already exists, and wait for completion
$bucket->manager()->createN1qlPrimaryIndex('', false, false);
echo "Primary index has been created\n";
} catch (CouchbaseException $e) {
printf("Couldn't create index. Maybe it already exists? (code: %d)\n", $e->getCode());
}
// Query with parameters
$query = CouchbaseN1qlQuery::fromString("SELECT * FROM `$bucketName` WHERE \$p IN interests");
$query->namedParams(array("p" => "African Swallows"));
echo "Parameterized query:\n";
var_dump($query);
$rows = $bucket->query($query);
echo "Results:\n";
var_dump($rows);
The console output should look similar to this:
Storing u:king_arthur object(CouchbaseMetaDoc)#4 (5) { ["error"]=> NULL ["value"]=> NULL ["flags"]=> NULL ["cas"]=> string(10) "eldhjkkzcw" ["token"]=> NULL } Getting back u:king_arthur object(stdClass)#5 (2) { ["email"]=> string(24) "[email protected]" ["interests"]=> array(1) { [0]=> string(16) "African Swallows" } } Replacing u:king_arthur object(CouchbaseMetaDoc)#6 (5) { ["error"]=> NULL ["value"]=> object(stdClass)#5 (2) { ["email"]=> string(24) "[email protected]" ["interests"]=> array(2) { [0]=> string(16) "African Swallows" [1]=> string(5) "PHP 7" } } ["flags"]=> int(33554438) ["cas"]=> string(10) "eldhjkkzcw" ["token"]=> NULL } Creating primary index Primary index has been created Parameterized query: object(CouchbaseN1qlQuery)#8 (2) { ["options"]=> array(2) { ["statement"]=> string(45) "SELECT * FROM `bucket-name` WHERE $p IN interests" ["$p"]=> string(16) "African Swallows" } ["adhoc"]=> bool(true) } Results: object(stdClass)#11 (3) { ["rows"]=> array(1) { [0]=> object(stdClass)#10 (1) { ["bucket-name"]=> object(stdClass)#9 (2) { ["email"]=> string(24) "[email protected]" ["interests"]=> array(2) { [0]=> string(16) "African Swallows" [1]=> string(5) "PHP 7" } } } } ["status"]=> string(7) "success" ["metrics"]=> array(4) { ["elapsedTime"]=> string(11) "11.623318ms" ["executionTime"]=> string(11) "11.605128ms" ["resultCount"]=> int(1) ["resultSize"]=> int(220) } }
API Reference
The API reference is generated for each version.
The API reference for version 2.4.4
is at http://docs.couchbase.com/sdk-api/couchbase-php-client-2.4.4/files/couchbase.html