home shape

Tutorial: PHP in 10 minutes

This is a short tutorial for using ArangoDB from PHP. In less than 10 minutes you can learn how to use ArangoDB with the ArangoDB PHP driver.

Note: this tutorial ws written for ArangoDB 3 series and might not work for older version

This tutorial assumes that you have an ArangoDB server listening on IP 127.0.0.1 and the default port 8529.

background img reverse min

Install the PHP client

We’ll be installing the ArangoDB PHP client from composer via packagist.

On the command-line issue the following command:

curl -s http://getcomposer.org/installer | php

This will put the composer.phar file into the current directory. Next, create a new directory for your project, e.g. arangophp, and move into it:

mkdir arangophp && cd arangophp
composer get

Then use composer’s init command to define the initial dependencies for your project:

php ../composer.phar init
background img

This will fire up composer’s interactive config generator:

  • Package Name: Can be left blank for the proposed name
  • Description: Can be left blank
  • Author: Can be left blank for the proposed name
  • Minimum Stability: dev
  • License: Can be left blank
  • Would you like to define dependencies?: Type yes
  • Search for a package: Type triagens/arangodb-php
  • Enter package # to add , or the complete package name if it is not listed: Choose triagens/arangodb via numbers, in this case 0
  • Enter the version constraint to require (or leave blank to use the latest version): ^3.0
  • Search for package: Can be left blank
  • Would you like to define your dev dependencies?: Type no
  • Search for package: Can be left blank
  • Do you confirm generation?: Type yes

After filling out the config generator you need to tell composer to install all dependencies:

php ../composer.phar update

This will download the ArangoDB-PHP driver code into the “vendor” subdirectory in your project.

composer update
background img reverse min

Setting up the connection to the server

With the ArangoDB-PHP driver downloaded, we can now write some PHP code to exercise it.

Let’s create a PHP script that connects to ArangoDB. Put the following code into a file named test.php:

 'tcp://127.0.0.1:8529',
    // authorization type to use (currently supported: 'Basic')
    ConnectionOptions::OPTION_AUTH_TYPE => 'Basic',
    // user for basic authorization
    ConnectionOptions::OPTION_AUTH_USER => 'root',
    // password for basic authorization
    ConnectionOptions::OPTION_AUTH_PASSWD => '',
    // connection persistence on server. can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)
    ConnectionOptions::OPTION_CONNECTION => 'Close',
    // connect timeout in seconds
    ConnectionOptions::OPTION_TIMEOUT => 3,
    // whether or not to reconnect when a keep-alive connection has timed out on server
    ConnectionOptions::OPTION_RECONNECT => true,
    // optionally create new collections when inserting documents
    ConnectionOptions::OPTION_CREATE => true,
    // optionally create new collections when inserting documents
    ConnectionOptions::OPTION_UPDATE_POLICY => UpdatePolicy::LAST,
);
 
// open connection
$connection = new Connection($connectionOptions);

Some details you should know about the code:

  • Auto-generates a new collection if OPTION_CREATE is set true
  • If OPTION_CREATE is set false an error will appear
  • The last update of a document overwrites the previous one if OPTION_UPDATE_POLICY is set true
  • If OPTION_UPDATE_POLICY is set false an error will appear
  • We did not specify a certain database, so the connection points to the default database _system
Hint: the default connection is to http://127.0.0.1:8529.

Creating a collection

Now let’s create a collection. Append the following code to the file test.php:

// create a new collection
$collectionName = "firstCollection";
$collection = new Collection($collectionName);
$collectionHandler = new CollectionHandler($connection);
 
if ($collectionHandler->has($collectionName)) {
  // drops an existing collection with the same name to make
  // tutorial repeatable
  $collectionHandler->drop($collectionName);
}
 
$collectionId = $collectionHandler->create($collection);
$documentHandler = new DocumentHandler($connection);
 
var_dump($collectionId);

Some details you should know about the code:

  • The collectionHandler provides methods for dealing with collections
  • create() creates the collection
  • $connection is the previous defined connection to our new database
  • $collectionId is the Identifier of the collection created by the database
background img

Creating a document

To create a document we use our previously created database and collection. Now let’s append some code to test.php that saves a document:

// create a document with some attributes
$document = new Document();
$document->set("a", "Foo");
$document->set("b", "bar");
 
// save document in collection
$documentId = $documentHandler->save($collectionName, $document);

Some details you should know about the code:

  • collection "firstCollection" (defined in $collectionName) is created automatically, if it does not exist
  • set() sets document properties (key and value)
  • save() creates the document
  • $connection is the previous defined connection
  • $documentId is the Identifier of the document created by the database

Running this code will create a document in collection “firstCollection”.

Read a document

Let’s read back the created document and print it, by appending the following code to test.php:

// read document
$document = $documentHandler->get($collectionName, $documentId);
var_dump($document);

The result should look something like this:

Some details you should know about the code:

  • to retrieve a certain document, you have to know its id
  • get() returns the document defined by its id $documentId and the containing collection $collectionName
  • instead of the name of the collection, you can also use the id of the collection
background img reverse min

Update the document

Let’s add an attribute “c” with value “qux” to the current $document:

// update document
$document->set("c", "qux");
$documentHandler->update($document);

Some details you should know about the code:

  • There is no need to send the name of the collection as a parameter, because this information is already stored in the document

Read the modified document

To read the document again, append the following code:

// read document again
$document = $documentHandler->get($collectionName, $documentId);
var_dump($document);

The result should look something like this:

Create some additional data

We will now run a simple for-loop to insert more test documents into the collection:

// additional data via for-loop
for ($i = 0; $i < 100; $i++) { 
    $document = new Document(); 
    $document->set("_key", "doc_" . $i . mt_rand());
    $val = false;
    if ($i%2 === 0) {
        $val = true;
    }
    $document->set("even", $val);
    $documentHandler->save($collectionName, $document);
}
background img

List of all documents

To fetch the identifiers of all stored documents from the collections, append the following code to the script:

// list all documents
$documents = $collectionHandler->all($collectionId);
 
var_dump($documents);

Deleting a document

To remove a document, use the remove method as follows:

$documentDelete = $documentHandler->remove($document);
var_dump($documentDelete);
Almost done!

Now you can work through the next four steps as a bonus. These steps will show you how to work with AQL, the ArangoDB Query Language from PHP. If you want to stop here jump to the last section and learn more.

Executing AQL queries

// execute AQL queries
$query = 'FOR x IN firstCollection RETURN x._key'; 
$statement = new Statement(
    $connection,
    array(
        "query"     => $query,
        "count"     => true,
        "batchSize" => 1000,
        "sanitize"  => true
    )
);
 
$cursor = $statement->execute();
$resultingDocuments = array();
 
foreach ($cursor as $key => $value) {
    $resultingDocuments[$key] = $value;
}
 
var_dump($resultingDocuments);

The result should look something like this:

Some details you should know about the code:

  • execute() sends a given AQL (defined in $query) to the server and executes it
  • FOR x IN firstCollection iterates over all entries in the collection
  • RETURN x._key will return the attribute “_key” of each document
  • The order of documents is not guaranteed as no SORT instruction is used in the AQL query
background img reverse min

Inserting documents via AQL

It is also possible to use AQL for inserting documents into collections. The following code will issue an AQL INSERT state to insert one document.

// insert document via AQL
$document = array(
    "_key" => "firstDocument",
    "a"    => "Foo",
    "b"    => "bar"
);
 
$query = 'INSERT @doc INTO firstCollection RETURN NEW';
 
$statement = new Statement(
    $connection,
    array(
        "query"     => $query,
        "count"     => true,
        "batchSize" => 1,
        "sanitize"  => true,
        "bindVars"  => array("doc" => $document)
    )
);
 
$cursor = $statement->execute();
$resultingDocuments = array();
 
foreach ($cursor as $key => $value) {
    $resultingDocuments[$key] = $value;
}
var_dump($resultingDocuments);

Some details you should know about the code:

  • INSERT @doc INTO firstCollection saves the document into the collection
  • @doc defines a bind parameter in AQL
  • bindVars defines the content of all parameters

Update a document via AQL

We can also use AQL to update existing documents in the collection:

// update document via AQL
$document = array(
    "c" => "qux",
);
$query = "UPDATE @key WITH @doc IN firstCollection RETURN NEW";
$statement = new Statement(
    $connection,
    array(
        "query"     => $query,
        "count"     => true,
        "batchSize" => 1,
        "sanitize"  => true,
        "bindVars"  => array("doc" => $document, "key" => "firstDocument")
    )
);
 
$cursor = $statement->execute();
 
$resultingDocuments = array();
 
foreach ($cursor as $key => $value) {
    $resultingDocuments[$key] = $value;
}
var_dump($resultingDocuments);

Some details you should know about the code:

  • @doc defines a parameter for the update values in AQL
  • @key defines a parameter for the document’s key in AQL
background img

Deleting documents via AQL

AQL can also be used to delete documents from the collection. We use a FILTER condition to remove just specific documents:

// delete document via AQL
$query = "FOR x IN @@collection FILTER x.d == 'qux' REMOVE x IN @@collection RETURN OLD";
$statement = new Statement(
    $connection,
    array(
        "query"     => $query,
        "count"     => true,
        "batchSize" => 1,
        "sanitize"  => true,
        "bindVars"  => array("@collection" => "firstCollection")
    )
);
 
$cursor = $statement->execute();
var_dump($cursor);

Some details you should know about the code:

  • FILTER condition only iterates over documents matching the condition
  • REMOVE x IN firstCollection deletes a document (matching the filter)
  • @@collection defines a parameter for a collection name, note the @@

Learn more

Now you know how to work with ArangoDB. Some additional info: