SlideShare a Scribd company logo
1 of 28
USING RIAK WITH PHP
    Front Range PHP Users Group - May 12th, 2010
           Jon Meredith - Basho Technologies
        jmeredith@basho.com / @jon_meredith
RIAK BY EXAMPLE


• URL   Shortener Example in PHP (thx Sean Cribbs)

• Creates   a short URL that redirects to the real thing

• Demonstrates    buckets, get and put.
<html>
            SUBMIT-TO-SELF FORM
<h1>URL Shortener</h1>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
URL <input type="text" name="url" size="60"
           value="<?php echo $url; ?>">
<input type="submit" name="submit" value="Shtn!"><br/>
<?php
if (isset($shtn)) {
	 $surl = "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]"+
           "$_SERVER[PHP_SELF]/$shtn";
	 echo "Shortened <a href='$surl'>$surl</a><br/>";
}
if (isset($notice)) {
	 echo "<em>$notice</em><br/>";
}
?>
</form>
</html>
ON POST
<?php
include_once "riak.php";
// snip...

// Responding to a post
} elseif (isset($_POST['url'])) {
	 $url = $_POST['url'];
	 $shtn = shorten($url);
	
	 $client = new RiakClient('localhost', 8098);
	 $bucket = $client->bucket('shtn');
	 $object = $bucket->newBinary($shtn, $url, 'text/plain');
	 $object->store();
}
?>
ON GET
if ($_SERVER["REQUEST_METHOD"] == 'GET' and
    isset($_SERVER["PATH_INFO"])) {
	 $client = new RiakClient('localhost', 8098);
	 $bucket = $client->bucket('shtn');
	 $path_els = explode('/', $_SERVER["PATH_INFO"]);
	 $key = $path_els[1];
	 $obj = $bucket->getBinary($key);
	 if ($obj->exists())
	 {
	 	 $lurl = $obj->getData();
	 	 header("Location: $lurl");
	 	 exit;
	 }
	 else
	 {
	 	 $notice = "Unknown redirect for $key";
	 }
}
STUPID COLLISION PRONE SHORTENER
                 DO NOT USE



// cheap and cheerful shortener - takes hash with crc32,
// converts to base64 and trims non a-zA-Z0-9 characters
function shorten($url) {
	 $hash = hash("crc32", $url, true);
	 $str = base64_encode($hash);
	 return preg_replace('/[^a-zA-Z0-9]/', '', $str);
}
SHTN DEMO
RIAK & PHP


• PHP    client http://bitbucket.org/basho/riak-php-client

• Uses   Riak’s RESTful HTTP interface

• Pure   PHP - requires the cURL module to be installed
RIAK PHP API


• RiakClient   - a connection to a single server

• RiakBucket   - access to bucket properties/objects stored

• RiakObject    - a key/value/metadata object
RIAK MATH

•N     - number of replicas

•R   - number of reads

•W     - number of writes

• DW     - durable writes

• As   long as R+W > N you read your writes
RIAKCLIENT CLASS

• Create   connection to a server
 $client = new RiakClient(HOST, PORT);
 assert($client->isAlive());



• Create   a RiakBucket object
 $bucket = $client->bucket('bucket');



• Get/Change      Defaults
 $client->getR();	 $client->getW();	$client->getDW();
 $client->setR(1);	 $client->setW(3);	client->setDW(1);
                                     $
RIAK BUCKETS

• Buckets   group related keys together.

• Finest   level you can configure Riak at

  •n   value - number of replicas

  • allow_mult    - return conflicts to client

  • r/w/dw    - successful reads/writes/durable writes
RIAKBUCKET CLASS


• Retrieve       objects
 $obj1   =   $bucket->get("missing");
 $obj1   =   $bucket->get("missing", $rVal);
 $obj2   =   $bucket->getBinary('foo2');
 $obj2   =   $bucket->getBinary('foo2', $rVal);



• Create       Objects
 $obj1 = bucket->newObject('foo', $structuredData);
 $obj2 = $bucket->newBinary('foo1', $binaryData);
MORE RIAKBUCKET


• Modify   bucket properties
 $bucket->getAllowMultiples();   $bucket->setAllowMultiples(TRUE);
 $bucket->getNVal();             $bucket->setNVal(3);



• Modify   per-bucket defaults
 $bucket->getR();	 $bucket->getW();	$bucket->getDW();
 $bucket->setR(1);	 $bucket->setW(3);	bucket->setDW(1);
                                     $
RIAK OBJECTS

• RiakObjects     hold bucket name, keys, values and metadata.

• Metadata    includes content type and links.

• By  default objects serialize using JSON
 ... can prevent using ‘binary’ objects
 $bucket->getBinary($key); $bucket->newBinary($key);
RIAKOBJECT CLASS


• Access   key/data/metadata
 $object->getKey(); $object->getBucket();
 $object->getContentType(); $object->getLinks();
 $object->getData();



• Change    data/metadata
 $object->setContentType($contentType);
 $object->setData($data);
 $object->addLink($obj2,$tag);
 $object->removeLink($obj2, $tag);
MORE RIAKOBJECT

• Store   on server
 $obj->store();



• Reload   from server
 $obj->reload();



• Delete   from server
 $obj->delete();



• Clear   contents data/metadata (but not bucket/key/vclock)
 $obj->clear();
LINKS

•A  Link store a one-way relationship between two objects,
 similar to a hyperlink.

•A   link is a bucket & key plus a user-supplied tag.

• Objects   can have multiple links.

• Riak
     supports link walking - server side
 - match on bucket or tag
LINKS EXAMPLE

people/alice                    vip/claire
                    friend




               [no tag]      [no tag]   friend



                    friend

people/bob                   people/dean         Images http://www.openclipart.org
CREATING LINKS

• Create   objects with some links
 $people = $client->bucket('people');
 $vips = $client->bucket('vips');
 $alice = $people->newObject("alice", array(name => 'Alice'))->store();
 $bob = $people->newObject("bob", array(name => 'Bob'))->store();
 $claire = $vip->newObject("claire", array(name => 'Claire'))->
                    addLink($alice, 'friend')->
                    store();
 $dean = $people->newObject("dean", array(name => 'Dean'))->
                  addLink($alice)->
                  addLink($bob, 'friend')->
                  addLink($claire, 'friend')->
                  addLink($claire)->
                  store();
LINK WALKING
• Walk   the links
 $resultObjects = $object->link($bucket='_', $tag='_', $keep=FALSE);
 $bucket - match on a bucket name, '_' matches all
 $tag - match on a link tag, '_' matches all
 $keep - return results - last link always TRUE.



• Examples
 // Dean’s links array of $alice, $bob, $claire, $claire (duplicate)
 $deans_links = $dean->link('_')->run();
 // Dean’s friends array of $bob, $claire
 $deans_friends = $dean->link('_','friend')->run();
 // Dean’s VIPs array of $claire
 $deans_vips = $dean->link('vip’)->run();
 // Friends of Dean’s friends array of $alice
 $deans_fofs = $dean->link('_','friend')->link('_','friend')->run();
 // friends within 2 degrees of separation - array(array($bob, $claire), $alice)
 $deans_2degs = $dean->link('_','friend', TRUE)->link('_','friend', TRUE)->run();
LINK WALKING DEMO



• http://github.com/schofield/riak_php_app

• Created   by Grant Schofield, Developer Advocate @ Basho
RIAK MAP/REDUCE

• Map/Reduce     allows you to query Riak

• Map   function selects/transforms data you want

• Reduce    function combines the output of the map function

• Provide   your own functions (in erlang or javascript) or use the
 builtins
MAP/REDUCE EXAMPLE

$bucket->newObject("foo", 2)->store();
$bucket->newObject("bar", 3)->store();
$bucket->newObject("baz", 4)->store();

# Run the map...
$result = $client->
    add($bucket->name)->
    map("Riak.mapValuesJson") ->
    reduce("Riak.reduceSum")->
    run();
test_assert($result == array(9));
SUPPLY YOUR OWN MAPS
•   Javascript map functions get passed an object
    {
     "bucket":BucketAsString,
     "key":KeyAsString,
     "vclock":VclockAsString,
     "values":[{"metadata":{"X-Riak-VTag":VtagAsString,
                              "X-riak-Last-Modified":LastModAsString,
                       ...other metadata...
                      },
              "data":ObjectData
            },
            ...other metadata/data values (siblings)...]
    }


•   Returns an array of results
RETURNS KEYS WITH SPACES
   $map = "function(obj) {
       if (obj.key.indexOf(' ') != -1) {
           return [obj.key];
       } else {
           return [];
       }
   }";
   $result = $client->
       add($bucket->name)->
       map($map) ->
       reduce("Riak.reduceSort")->
       run();
SUPPLY YOUR OWN REDUCE
  $reduceMax = "function(values, arg) {
        values.sort().reverse();
        return [values[0]];
      }";
  $result = $client->
      add($bucket->name)->
      map("Riak.mapValuesJson") ->
      reduce($reduceMax)->
      run();
OVER TO YOU...


• Website    http://riak.basho.com

• Mailing   list riak-users@basho.com

• #riak   on FreeNode

• Twitter   @basho (and it follows our devs)

More Related Content

What's hot

Resource Routing in ExpressionEngine
Resource Routing in ExpressionEngineResource Routing in ExpressionEngine
Resource Routing in ExpressionEngineMichaelRog
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Kris Wallsmith
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016Kacper Gunia
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201Fabien Potencier
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionAdam Trachtenberg
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014
(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014
(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014Amazon Web Services
 
ATK 'Beyond The Pizza Guides'
ATK 'Beyond The Pizza Guides'ATK 'Beyond The Pizza Guides'
ATK 'Beyond The Pizza Guides'Ibuildings
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created itPaul Bearne
 
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012Amazon Web Services
 
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Hiroshi Shibamura
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0Elena Kolevska
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel MakhrinskyDrupalCampDN
 
Introduction to Riak and Ripple (KC.rb)
Introduction to Riak and Ripple (KC.rb)Introduction to Riak and Ripple (KC.rb)
Introduction to Riak and Ripple (KC.rb)Sean Cribbs
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 

What's hot (20)

Resource Routing in ExpressionEngine
Resource Routing in ExpressionEngineResource Routing in ExpressionEngine
Resource Routing in ExpressionEngine
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3
 
The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016The IoC Hydra - Dutch PHP Conference 2016
The IoC Hydra - Dutch PHP Conference 2016
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Dirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP ExtensionDirty Secrets of the PHP SOAP Extension
Dirty Secrets of the PHP SOAP Extension
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014
(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014
(DEV305) Building Apps with the AWS SDK for PHP | AWS re:Invent 2014
 
ATK 'Beyond The Pizza Guides'
ATK 'Beyond The Pizza Guides'ATK 'Beyond The Pizza Guides'
ATK 'Beyond The Pizza Guides'
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created it
 
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012
 
The IoC Hydra
The IoC HydraThe IoC Hydra
The IoC Hydra
 
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
 
Redis for your boss 2.0
Redis for your boss 2.0Redis for your boss 2.0
Redis for your boss 2.0
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
 
Redis for your boss
Redis for your bossRedis for your boss
Redis for your boss
 
Introduction to Riak and Ripple (KC.rb)
Introduction to Riak and Ripple (KC.rb)Introduction to Riak and Ripple (KC.rb)
Introduction to Riak and Ripple (KC.rb)
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
DBI
DBIDBI
DBI
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 

Similar to PHP API

The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Workhorse Computing
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011Alessandro Nadalin
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
 
Leveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPLeveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPJeremy Kendall
 
Undercover Pods / WP Functions
Undercover Pods / WP FunctionsUndercover Pods / WP Functions
Undercover Pods / WP Functionspodsframework
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aidawaraiotoko
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018Adam Tomat
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of TransductionDavid Stockton
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal APIAlexandru Badiu
 
DBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちDBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちRyo Miyake
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Zazzy WordPress Navigation WordCamp Milwaukee
Zazzy WordPress Navigation WordCamp MilwaukeeZazzy WordPress Navigation WordCamp Milwaukee
Zazzy WordPress Navigation WordCamp MilwaukeeRachel Baker
 

Similar to PHP API (20)

The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
XQuery Rocks
XQuery RocksXQuery Rocks
XQuery Rocks
 
php2.pptx
php2.pptxphp2.pptx
php2.pptx
 
Leveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHPLeveraging the Power of Graph Databases in PHP
Leveraging the Power of Graph Databases in PHP
 
Undercover Pods / WP Functions
Undercover Pods / WP FunctionsUndercover Pods / WP Functions
Undercover Pods / WP Functions
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
 
Learning the basics of the Drupal API
Learning the basics of the Drupal APILearning the basics of the Drupal API
Learning the basics of the Drupal API
 
Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
 
DBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たちDBIx::Skinnyと仲間たち
DBIx::Skinnyと仲間たち
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Zazzy WordPress Navigation WordCamp Milwaukee
Zazzy WordPress Navigation WordCamp MilwaukeeZazzy WordPress Navigation WordCamp Milwaukee
Zazzy WordPress Navigation WordCamp Milwaukee
 
Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09Spl Not A Bridge Too Far phpNW09
Spl Not A Bridge Too Far phpNW09
 

Recently uploaded

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Fact vs. Fiction: Autodetecting Hallucinations in LLMs
Fact vs. Fiction: Autodetecting Hallucinations in LLMsFact vs. Fiction: Autodetecting Hallucinations in LLMs
Fact vs. Fiction: Autodetecting Hallucinations in LLMsZilliz
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 

Recently uploaded (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Fact vs. Fiction: Autodetecting Hallucinations in LLMs
Fact vs. Fiction: Autodetecting Hallucinations in LLMsFact vs. Fiction: Autodetecting Hallucinations in LLMs
Fact vs. Fiction: Autodetecting Hallucinations in LLMs
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 

PHP API

  • 1. USING RIAK WITH PHP Front Range PHP Users Group - May 12th, 2010 Jon Meredith - Basho Technologies jmeredith@basho.com / @jon_meredith
  • 2. RIAK BY EXAMPLE • URL Shortener Example in PHP (thx Sean Cribbs) • Creates a short URL that redirects to the real thing • Demonstrates buckets, get and put.
  • 3. <html> SUBMIT-TO-SELF FORM <h1>URL Shortener</h1> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> URL <input type="text" name="url" size="60" value="<?php echo $url; ?>"> <input type="submit" name="submit" value="Shtn!"><br/> <?php if (isset($shtn)) { $surl = "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]"+ "$_SERVER[PHP_SELF]/$shtn"; echo "Shortened <a href='$surl'>$surl</a><br/>"; } if (isset($notice)) { echo "<em>$notice</em><br/>"; } ?> </form> </html>
  • 4. ON POST <?php include_once "riak.php"; // snip... // Responding to a post } elseif (isset($_POST['url'])) { $url = $_POST['url']; $shtn = shorten($url); $client = new RiakClient('localhost', 8098); $bucket = $client->bucket('shtn'); $object = $bucket->newBinary($shtn, $url, 'text/plain'); $object->store(); } ?>
  • 5. ON GET if ($_SERVER["REQUEST_METHOD"] == 'GET' and isset($_SERVER["PATH_INFO"])) { $client = new RiakClient('localhost', 8098); $bucket = $client->bucket('shtn'); $path_els = explode('/', $_SERVER["PATH_INFO"]); $key = $path_els[1]; $obj = $bucket->getBinary($key); if ($obj->exists()) { $lurl = $obj->getData(); header("Location: $lurl"); exit; } else { $notice = "Unknown redirect for $key"; } }
  • 6. STUPID COLLISION PRONE SHORTENER DO NOT USE // cheap and cheerful shortener - takes hash with crc32, // converts to base64 and trims non a-zA-Z0-9 characters function shorten($url) { $hash = hash("crc32", $url, true); $str = base64_encode($hash); return preg_replace('/[^a-zA-Z0-9]/', '', $str); }
  • 8. RIAK & PHP • PHP client http://bitbucket.org/basho/riak-php-client • Uses Riak’s RESTful HTTP interface • Pure PHP - requires the cURL module to be installed
  • 9. RIAK PHP API • RiakClient - a connection to a single server • RiakBucket - access to bucket properties/objects stored • RiakObject - a key/value/metadata object
  • 10. RIAK MATH •N - number of replicas •R - number of reads •W - number of writes • DW - durable writes • As long as R+W > N you read your writes
  • 11. RIAKCLIENT CLASS • Create connection to a server $client = new RiakClient(HOST, PORT); assert($client->isAlive()); • Create a RiakBucket object $bucket = $client->bucket('bucket'); • Get/Change Defaults $client->getR(); $client->getW(); $client->getDW(); $client->setR(1); $client->setW(3); client->setDW(1); $
  • 12. RIAK BUCKETS • Buckets group related keys together. • Finest level you can configure Riak at •n value - number of replicas • allow_mult - return conflicts to client • r/w/dw - successful reads/writes/durable writes
  • 13. RIAKBUCKET CLASS • Retrieve objects $obj1 = $bucket->get("missing"); $obj1 = $bucket->get("missing", $rVal); $obj2 = $bucket->getBinary('foo2'); $obj2 = $bucket->getBinary('foo2', $rVal); • Create Objects $obj1 = bucket->newObject('foo', $structuredData); $obj2 = $bucket->newBinary('foo1', $binaryData);
  • 14. MORE RIAKBUCKET • Modify bucket properties $bucket->getAllowMultiples(); $bucket->setAllowMultiples(TRUE); $bucket->getNVal(); $bucket->setNVal(3); • Modify per-bucket defaults $bucket->getR(); $bucket->getW(); $bucket->getDW(); $bucket->setR(1); $bucket->setW(3); bucket->setDW(1); $
  • 15. RIAK OBJECTS • RiakObjects hold bucket name, keys, values and metadata. • Metadata includes content type and links. • By default objects serialize using JSON ... can prevent using ‘binary’ objects $bucket->getBinary($key); $bucket->newBinary($key);
  • 16. RIAKOBJECT CLASS • Access key/data/metadata $object->getKey(); $object->getBucket(); $object->getContentType(); $object->getLinks(); $object->getData(); • Change data/metadata $object->setContentType($contentType); $object->setData($data); $object->addLink($obj2,$tag); $object->removeLink($obj2, $tag);
  • 17. MORE RIAKOBJECT • Store on server $obj->store(); • Reload from server $obj->reload(); • Delete from server $obj->delete(); • Clear contents data/metadata (but not bucket/key/vclock) $obj->clear();
  • 18. LINKS •A Link store a one-way relationship between two objects, similar to a hyperlink. •A link is a bucket & key plus a user-supplied tag. • Objects can have multiple links. • Riak supports link walking - server side - match on bucket or tag
  • 19. LINKS EXAMPLE people/alice vip/claire friend [no tag] [no tag] friend friend people/bob people/dean Images http://www.openclipart.org
  • 20. CREATING LINKS • Create objects with some links $people = $client->bucket('people'); $vips = $client->bucket('vips'); $alice = $people->newObject("alice", array(name => 'Alice'))->store(); $bob = $people->newObject("bob", array(name => 'Bob'))->store(); $claire = $vip->newObject("claire", array(name => 'Claire'))-> addLink($alice, 'friend')-> store(); $dean = $people->newObject("dean", array(name => 'Dean'))-> addLink($alice)-> addLink($bob, 'friend')-> addLink($claire, 'friend')-> addLink($claire)-> store();
  • 21. LINK WALKING • Walk the links $resultObjects = $object->link($bucket='_', $tag='_', $keep=FALSE); $bucket - match on a bucket name, '_' matches all $tag - match on a link tag, '_' matches all $keep - return results - last link always TRUE. • Examples // Dean’s links array of $alice, $bob, $claire, $claire (duplicate) $deans_links = $dean->link('_')->run(); // Dean’s friends array of $bob, $claire $deans_friends = $dean->link('_','friend')->run(); // Dean’s VIPs array of $claire $deans_vips = $dean->link('vip’)->run(); // Friends of Dean’s friends array of $alice $deans_fofs = $dean->link('_','friend')->link('_','friend')->run(); // friends within 2 degrees of separation - array(array($bob, $claire), $alice) $deans_2degs = $dean->link('_','friend', TRUE)->link('_','friend', TRUE)->run();
  • 22. LINK WALKING DEMO • http://github.com/schofield/riak_php_app • Created by Grant Schofield, Developer Advocate @ Basho
  • 23. RIAK MAP/REDUCE • Map/Reduce allows you to query Riak • Map function selects/transforms data you want • Reduce function combines the output of the map function • Provide your own functions (in erlang or javascript) or use the builtins
  • 24. MAP/REDUCE EXAMPLE $bucket->newObject("foo", 2)->store(); $bucket->newObject("bar", 3)->store(); $bucket->newObject("baz", 4)->store(); # Run the map... $result = $client-> add($bucket->name)-> map("Riak.mapValuesJson") -> reduce("Riak.reduceSum")-> run(); test_assert($result == array(9));
  • 25. SUPPLY YOUR OWN MAPS • Javascript map functions get passed an object { "bucket":BucketAsString, "key":KeyAsString, "vclock":VclockAsString, "values":[{"metadata":{"X-Riak-VTag":VtagAsString, "X-riak-Last-Modified":LastModAsString, ...other metadata... }, "data":ObjectData }, ...other metadata/data values (siblings)...] } • Returns an array of results
  • 26. RETURNS KEYS WITH SPACES $map = "function(obj) { if (obj.key.indexOf(' ') != -1) { return [obj.key]; } else { return []; } }"; $result = $client-> add($bucket->name)-> map($map) -> reduce("Riak.reduceSort")-> run();
  • 27. SUPPLY YOUR OWN REDUCE $reduceMax = "function(values, arg) { values.sort().reverse(); return [values[0]]; }"; $result = $client-> add($bucket->name)-> map("Riak.mapValuesJson") -> reduce($reduceMax)-> run();
  • 28. OVER TO YOU... • Website http://riak.basho.com • Mailing list riak-users@basho.com • #riak on FreeNode • Twitter @basho (and it follows our devs)

Editor's Notes