Monday, February 4, 2013

Accessing Couchbase from PHP on your Mac!

Given that I've already blogged about how to use PHP from IIS on Windows I figured I should do another blog post for people using Mac OSX. Luckily for us Mac OSX ships with both Apache2 and PHP, so its fairly easy to start using it.

Our PHP extension is built on top of libcouchbase, so the first thing we need to do is to install that. I guess most Mac users are already using homebrew to get stuff onto their Mac so installing libcouchbase is simply a matter of:

trond@ok ~> brew install libcouchbase

The next thing we need to do is to download the PHP extension and install it somewhere
locally. Personally I do like to put such modules in it's own directory, so I'm going to use /opt/couchbase/lib for now:

trond@ok ~> cd /tmp
trond@ok /tmp> wget
trond@ok tmp> tar xfz php-ext-couchbase-1.1.2-macosx-x86_64.tar.gz
trond@ok /tmp> sudo mkdir -p /opt/couchbase/lib
trond@ok /tmp> sudo cp php-ext-couchbase/ /opt/couchbase/lib

With the plugin in place we need to tell php to load it. To do so add the following line in /etc/php.ini:


This should be enough to use Couchbase from PHP, so lets go ahead and verify that it works:

trond@ok ~> php -i | grep couchbase
couchbase support => enabled
couchbase.compression_factor => 1.3 => 1.3
couchbase.compression_threshold => 2000 => 2000
couchbase.compressor => none => none
couchbase.durability_default_poll_interval => 100000 => 100000
couchbase.durability_default_timeout => 40000000 => 40000000
couchbase.serializer => php => php
couchbase.view_timeout => 75 => 75

Yay! We're almost there. To enable PHP in Apache2 we need to uncomment the following line in /etc/apache2/httpd.conf

#LoadModule php5_module libexec/apache2/

Remove the # and save the file. We need to start (or restart) apache2 for the changes to take effect:

trond@ok ~> sudo apachectl start

So lets check that it works! Go ahead and create the following file in $HOME/Sites/phpinfo.php

<?php phpinfo(); ?>

and access it: http://localhost/~your-username/phpinfo.php

You should get a page with a lot of text, and if you search the page you should find a section with information about the Couchbase extension.

Now that we've got something that works, lets create a small example page that actually use the extension. Go ahead and create a file named $HOME/Sites/index.php with the following content:

        <h1>This page has been accessed:
            try {
                $cb = new Couchbase();
                print($cb->increment("counter", 1, true, 0, 0));
            } catch (CouchbaseException $ex) {

If you have a Couchbase server running on the same machine you should be able to access this page through http://localhost/~yourname/ and for each time you access the page the counter should increase.

I'll write another blog post with examples that utilize the API.

No comments:

Post a Comment