{"id":13795406,"url":"https://github.com/arangodb/arangodb-php","last_synced_at":"2025-04-13T07:48:36.982Z","repository":{"id":2725486,"uuid":"3720380","full_name":"arangodb/arangodb-php","owner":"arangodb","description":"PHP ODM for ArangoDB","archived":false,"fork":false,"pushed_at":"2023-04-05T19:15:15.000Z","size":7786,"stargazers_count":185,"open_issues_count":33,"forks_count":47,"subscribers_count":74,"default_branch":"devel","last_synced_at":"2025-04-13T07:48:32.827Z","etag":null,"topics":["arangodb","database","driver","nosql","php"],"latest_commit_sha":null,"homepage":"https://www.arangodb.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"ArchiDroid/android_frameworks_native","license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/arangodb.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2012-03-14T17:54:34.000Z","updated_at":"2025-03-20T20:25:46.000Z","dependencies_parsed_at":"2023-07-06T16:01:53.557Z","dependency_job_id":null,"html_url":"https://github.com/arangodb/arangodb-php","commit_stats":{"total_commits":853,"total_committers":27,"mean_commits":31.59259259259259,"dds":0.5920281359906213,"last_synced_commit":"db8b154f0e82f147945db3c8bcb52b922894db5d"},"previous_names":[],"tags_count":53,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arangodb%2Farangodb-php","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arangodb%2Farangodb-php/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arangodb%2Farangodb-php/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/arangodb%2Farangodb-php/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/arangodb","download_url":"https://codeload.github.com/arangodb/arangodb-php/tar.gz/refs/heads/devel","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248681494,"owners_count":21144700,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["arangodb","database","driver","nosql","php"],"created_at":"2024-08-03T23:00:55.978Z","updated_at":"2025-04-13T07:48:36.951Z","avatar_url":"https://github.com/arangodb.png","language":"PHP","funding_links":[],"categories":["Uncategorized"],"sub_categories":["Uncategorized"],"readme":"# ArangoDB-PHP - A PHP client for ArangoDB\n\nThis driver for ArangoDB, called the ArangoDB-PHP client,\nallows REST-based access to documents on the server. The _DocumentHandler_ class\nshould be used for these purposes. There is an example for REST-based documents\naccess in the [`examples/document.php`](examples/document.php) file.\n\nFurthermore, the PHP client also allows to issue more AQL complex queries using\nthe _Statement_ class. There is an example for this kind of statements in the\n[`examples/aql-query.php`](examples/aql-query.php) file.\n\nTo use the PHP client, you must include the file `autoloader.php` from the main\ndirectory. The autoloader cares about loading additionally required classes on\nthe fly. The autoloader can be nested with other autoloaders.\n\nThe ArangoDB PHP client is an API that allows you to send and retrieve documents\nfrom ArangoDB from out of your PHP application. The client library itself is\nwritten in PHP and has no further dependencies but just plain PHP 5.6\n(or higher).\n\nThe client library provides document and collection classes you can use to work\nwith documents and collections in an object-oriented fashion. When exchanging\ndocument data with the server, the library internally uses the\n[HTTP REST interface of ArangoDB](https://www.arangodb.com/docs/stable/http/index.html).\nThe library user does not have to care about this fact as all the details of the\nREST interface are abstracted by the client library.\n\n## Requirements\n\n- PHP version 5.6 or higher\n\nNote on PHP version support:\n\nThis driver ceases to support old PHP versions as soon as they have reached\nend-of-life status. Support is removed with the next minor or patch version of\nthe driver to be released.\n\nIn general, it is recommended to always use the latest PHP versions in order to\ntake advantage of all the improvements (especially in performance).\n\n## Important version information on ArangoDB-PHP\n\nThe ArangoDB-PHP driver version has to match with the ArangoDB version:\n\n- ArangoDB-PHP v3.8.x is on par with the functionality of ArangoDB v3.8.x\n- ArangoDB-PHP v3.9.x is on par with the functionality of ArangoDB v3.9.x\n\netc.\n\n## Installation using Composer or Git\n\nTo get started, you need PHP 5.6 or higher plus an ArangoDB server running on\nany host that you can access.\n\nThere are two alternative ways to get the ArangoDB PHP client:\n\n- Using Composer\n- Cloning the git repository\n\n### Alternative 1: Using Composer\n\nIf you use [Composer](https://getcomposer.org/), you can run the following\ncommand in a command-line to install the PHP client:\n\n```\ncomposer require triagens/arangodb\n```\n\n### Alternative 2: Cloning the Git repository\n\nWhen preferring this alternative, you need to have a\n[Git client](https://git-scm.com/downloads) installed. To clone the\nArangoDB-PHP client repository from GitHub, execute the following command in\nyour project directory:\n\n```\ngit clone \"https://github.com/arangodb/arangodb-php.git\"\n```\n\nThis creates an `arangodb-php` subdirectory in your current directory. It\ncontains all the files of the client library. It also includes a dedicated\nautoloader that you can use for autoloading the client libraries class files.\nTo invoke this autoloader, add the following line to your PHP files that need\nthe library:\n\n```php\nrequire 'arangodb-php/autoload.php';\n```\n\nThe ArangoDB-PHP client's autoloader only cares about its own class files and\ndoes not handle any other files. That means it is fully nestable with other\nautoloaders.\n\nIf you do not wish to include autoload.php to load and setup the autoloader, you\ncan invoke the autoloader directly:\n\n```php\nrequire 'arangodb-php/lib/ArangoDBClient/autoloader.php';\n\\ArangoDBClient\\Autoloader::init();\n```\n\n## Set up the connection\n\nIn order to use ArangoDB, you need to specify the connection options. You can do\nso by creating a PHP array `$connectionOptions`. Put this code into a file named\n`test.php` in your current directory:\n\n```php\n// use the following line when using Composer\n// require __DIR__ . '/vendor/composer/autoload.php';\n\n// use the following line when using git\nrequire __DIR__ . '/arangodb-php/autoload.php';\n\n// set up some aliases for less typing later\nuse ArangoDBClient\\Collection as ArangoCollection;\nuse ArangoDBClient\\CollectionHandler as ArangoCollectionHandler;\nuse ArangoDBClient\\Connection as ArangoConnection;\nuse ArangoDBClient\\ConnectionOptions as ArangoConnectionOptions;\nuse ArangoDBClient\\DocumentHandler as ArangoDocumentHandler;\nuse ArangoDBClient\\Document as ArangoDocument;\nuse ArangoDBClient\\Exception as ArangoException;\nuse ArangoDBClient\\ConnectException as ArangoConnectException;\nuse ArangoDBClient\\ClientException as ArangoClientException;\nuse ArangoDBClient\\ServerException as ArangoServerException;\nuse ArangoDBClient\\Statement as ArangoStatement;\nuse ArangoDBClient\\UpdatePolicy as ArangoUpdatePolicy;\n\n// set up some basic connection options\n$connectionOptions = [\n    // database name\n    ArangoConnectionOptions::OPTION_DATABASE =\u003e '_system',\n    // server endpoint to connect to\n    ArangoConnectionOptions::OPTION_ENDPOINT =\u003e 'tcp://127.0.0.1:8529',\n    // authorization type to use (currently supported: 'Basic')\n    ArangoConnectionOptions::OPTION_AUTH_TYPE =\u003e 'Basic',\n    // user for basic authorization\n    ArangoConnectionOptions::OPTION_AUTH_USER =\u003e 'root',\n    // password for basic authorization\n    ArangoConnectionOptions::OPTION_AUTH_PASSWD =\u003e '',\n    // connection persistence on server. can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)\n    ArangoConnectionOptions::OPTION_CONNECTION =\u003e 'Keep-Alive',\n    // connect timeout in seconds\n    ArangoConnectionOptions::OPTION_TIMEOUT =\u003e 3,\n    // whether or not to reconnect when a keep-alive connection has timed out on server\n    ArangoConnectionOptions::OPTION_RECONNECT =\u003e true,\n    // optionally create new collections when inserting documents\n    ArangoConnectionOptions::OPTION_CREATE =\u003e true,\n    // optionally create new collections when inserting documents\n    ArangoConnectionOptions::OPTION_UPDATE_POLICY =\u003e ArangoUpdatePolicy::LAST,\n];\n\n// turn on exception logging (logs to whatever PHP is configured)\nArangoException::enableLogging();\n\n$connection = new ArangoConnection($connectionOptions);\n```\n\nThis makes the client connect to ArangoDB\n\n- running on localhost (`OPTION_HOST`)\n- on the default port 8529 (`OPTION_PORT`)\n- with a connection timeout of 3 seconds (`OPTION_TIMEOUT`)\n\nWhen creating new documents in a collection that does not yet exist, you have\nthe following choices:\n\n- **auto-generate a new collection**:\n  if you prefer that, set `OPTION_CREATE` to `true`\n\n- **fail with an error**:\n  if you prefer this behavior, set `OPTION_CREATE` to `false`\n\nWhen updating a document that was previously/concurrently updated by another\nuser, you can select between the following behaviors:\n\n- **last update wins**:\n  if you prefer this, set `OPTION_UPDATE_POLICY` to last\n\n- **fail with a conflict error**:\n  if you prefer that, set `OPTION_UPDATE_POLICY` to conflict\n\n### Setting up Active Failover\n\nBy default, the PHP client connects to a single endpoint only, by specifying a\nstring value for the endpoint in the connection options, e.g.\n\n```php\n$connectionOptions = [\n    ArangoConnectionOptions::OPTION_ENDPOINT =\u003e 'tcp://127.0.0.1:8529'\n];\n```\n\nTo set up multiple servers to connect to, it is also possible to specify an\narray of servers instead:\n\n```php\n$connectionOptions = [\n    ArangoConnectionOptions::OPTION_ENDPOINT    =\u003e [ 'tcp://localhost:8531', 'tcp://localhost:8532', 'tcp://localhost:8530' ]\n];\n```\n\nUsing this option requires ArangoDB 3.3 or higher and the database running in\nActive Failover mode.\n\nThe driver tries to connect to the first server endpoint in the endpoints array\nby default, and only try the following servers if no connection can be\nestablished. If no connection can be made to any server, the driver throws an\nexception.\n\nAs it is unknown to the driver which server from the array is the current\nleader, the driver connects to the specified servers in array order by default.\nHowever, to spare a few unnecessary connection attempts to failed servers, it is\npossible to set up caching (using Memcached) for the server list. The cached\nvalue contains the last working server first, so that as few connection attempts\nas possible need to be made.\n\nIn order to use this caching, it is required to install the Memcached module for\nPHP, and to set up the following relevant options in the connection options:\n\n```php\n$connectionOptions = [\n    // memcached persistent id (will be passed to Memcached::__construct)\n    ArangoConnectionOptions::OPTION_MEMCACHED_PERSISTENT_ID =\u003e 'arangodb-php-pool',\n\n    // memcached servers to connect to (will be passed to Memcached::addServers)\n    ArangoConnectionOptions::OPTION_MEMCACHED_SERVERS       =\u003e [ [ '127.0.0.1', 11211 ] ],\n\n    // memcached options (will be passed to Memcached::setOptions)\n    ArangoConnectionOptions::OPTION_MEMCACHED_OPTIONS       =\u003e [ ],\n\n    // key to store the current endpoints array under\n    ArangoConnectionOptions::OPTION_MEMCACHED_ENDPOINTS_KEY =\u003e 'arangodb-php-endpoints'\n\n    // time-to-live for the endpoints array stored in memcached\n    ArangoConnectionOptions::OPTION_MEMCACHED_TTL           =\u003e 600\n];\n```\n\n## Create collections\n\n\u003e This is just to show how a collection is created. For these examples it is not\n\u003e needed to create a collection prior to inserting a document, as we set\n\u003e `ArangoConnectionOptions::OPTION_CREATE` to `true`.\n\nSo, after we get the settings, we can start with creating a collection. We\ncreate a collection named _users_.\n\nThe below code first sets up the collection locally in a variable name `$user`,\nand then pushes it to the server and returns the collection ID created by the\nserver:\n\n```php\n$collectionHandler = new ArangoCollectionHandler($connection);\n\n// clean up first\nif ($collectionHandler-\u003ehas('users')) {\n    $collectionHandler-\u003edrop('users');\n}\nif ($collectionHandler-\u003ehas('example')) {\n    $collectionHandler-\u003edrop('example');\n}\n\n// create a new collection\n$userCollection = new ArangoCollection();\n$userCollection-\u003esetName('users');\n$id = $collectionHandler-\u003ecreate($userCollection);\n\n// print the collection id created by the server\nvar_dump($id);\n// check if the collection exists\n$result = $collectionHandler-\u003ehas('users');\nvar_dump($result);\n```\n\n## Create documents\n\nAfter we created the collection, we can start with creating an initial document.\nWe create a user document in a collection named _users_. This collection does\nnot need to exist yet. The first document we insert in this collection creates\nthe collection on the fly. This is because we have set `OPTION_CREATE` to `true`\nin `$connectionOptions`.\n\nThe below code first sets up the document locally in a variable name `$user`,\nand then pushes it to the server and returns the document ID created by the\nserver:\n\n```php\n$handler = new ArangoDocumentHandler($connection);\n\n// create a new document\n$user = new ArangoDocument();\n\n// use set method to set document properties\n$user-\u003eset('name', 'John');\n$user-\u003eset('age', 25);\n$user-\u003eset('thisIsNull', null);\n$user-\u003eset('obj', ['nested' =\u003e True]);\n\n// use magic methods to set document properties\n$user-\u003elikes = ['fishing', 'hiking', 'swimming'];\n\n// send the document to the server\n$id = $handler-\u003esave('users', $user);\n\n// check if a document exists\n$result = $handler-\u003ehas('users', $id);\nvar_dump($result);\n\n// print the document id created by the server\nvar_dump($id);\nvar_dump($user-\u003egetId());\n```\n\nDocument properties can be set by using the `set()` method, or by directly\nmanipulating the document properties.\n\nAs you can see, sending a document to the server is achieved by calling the\n`save()` method on the client library's _DocumentHandler_ class. It needs the\ncollection name (_users_ in this case) plus the document object to be saved.\n`save()` returns the document ID as created by the server. The ID is a numeric\nvalue that might or might not fit in a PHP integer.\n\n## Add exception handling\n\nThe above code works but it does not check for any errors. To make it work in\nthe face of errors, we wrap it into some basic exception handlers:\n\n```php\ntry {\n    $handler = new ArangoDocumentHandler($connection);\n\n    // create a new document\n    $user = new ArangoDocument();\n\n    // use set method to set document properties\n    $user-\u003eset('name', 'John');\n    $user-\u003eset('age', 25);\n\n    // use magic methods to set document properties\n    $user-\u003elikes = ['fishing', 'hiking', 'swimming'];\n\n    // send the document to the server\n    $id = $handler-\u003esave('users', $user);\n\n    // check if a document exists\n    $result = $handler-\u003ehas('users', $id);\n    var_dump($result);\n\n    // print the document id created by the server\n    var_dump($id);\n    var_dump($user-\u003egetId());\n} catch (ArangoConnectException $e) {\n    print 'Connection error: ' . $e-\u003egetMessage() . PHP_EOL;\n} catch (ArangoClientException $e) {\n    print 'Client error: ' . $e-\u003egetMessage() . PHP_EOL;\n} catch (ArangoServerException $e) {\n    print 'Server error: ' . $e-\u003egetServerCode() . ':' . $e-\u003egetServerMessage() . ' ' . $e-\u003egetMessage() . PHP_EOL;\n}\n```\n\n## Retrieve documents\n\nTo retrieve a document from the server, the `get()` method of the\n_DocumentHandler_ class can be used. It needs the collection name plus a\ndocument ID. There is also the `getById()` method which is an alias for `get()`.\n\n```php\n// get the document back from the server\n$userFromServer = $handler-\u003eget('users', $id);\nvar_dump($userFromServer);\n\n/*\nThe result of the get() method is a Document object that you can use in an OO fashion:\n\nobject(ArangoDBClient\\Document)##6 (4) {\n    [\"_id\":\"ArangoDBClient\\Document\":private]=\u003e\n    string(15) \"2377907/4818344\"\n    [\"_rev\":\"ArangoDBClient\\Document\":private]=\u003e\n    int(4818344)\n    [\"_values\":\"ArangoDBClient\\Document\":private]=\u003e\n    array(3) {\n        [\"age\"]=\u003e\n        int(25)\n        [\"name\"]=\u003e\n        string(4) \"John\"\n        [\"likes\"]=\u003e\n        array(3) {\n            [0]=\u003e\n            string(7) \"fishing\"\n            [1]=\u003e\n            string(6) \"hiking\"\n            [2]=\u003e\n            string(8) \"swimming\"\n        }\n    }\n    [\"_changed\":\"ArangoDBClient\\Document\":private]=\u003e\n    bool(false)\n}\n*/\n```\n\nWhenever the document ID is yet unknown, but you want to fetch a document from\nthe server by any of its other properties, you can use the\n`CollectionHandler-\u003ebyExample()` method. It allows you to provide an example of\nthe document that you are looking for. The example should either be a _Document_\nobject with the relevant properties set, or, a PHP array with the properties\nthat you are looking for:\n\n```php\n// get a document list back from the server, using a document example\n$cursor = $collectionHandler-\u003ebyExample('users', ['name' =\u003e 'John']);\nvar_dump($cursor-\u003egetAll());\n```\n\nThis returns all documents from the specified collection (here: _users_) with\nthe properties provided in the example (here: that have an attribute `name` with\na value of `\"John\"`). The result is a cursor which can be iterated sequentially\nor completely. We have chosen to get the complete result set above by calling\nthe cursor's `getAll()` method.\n\n`CollectionHandler-\u003ebyExample()` returns multiple documents if the example is\nambiguous.\n\n## Update documents\n\nTo update an existing document, the `update()` method of the _DocumentHandler_\nclass can be used. In this example we want to:\n\n- set state to `'CA'`\n- change the `likes` array\n\n```php\n// update a document\n$userFromServer-\u003elikes = ['fishing', 'swimming'];\n$userFromServer-\u003estate = 'CA';\n\n$result = $handler-\u003eupdate($userFromServer);\nvar_dump($result);\n\n$userFromServer = $handler-\u003eget('users', $id);\nvar_dump($userFromServer);\n```\n\nTo remove an attribute using the `update()` method, an option has to be passed\ntelling it to not keep attributes with null values. In this example we want to\nremove the `age`:\n\n```php\n// update a document removing an attribute,\n// The 'keepNull'=\u003efalse option will cause ArangoDB to\n// remove all attributes in the document,\n// that have null as their value - not only the ones defined here\n\n$userFromServer-\u003elikes = ['fishing', 'swimming'];\n$userFromServer-\u003estate = 'CA';\n$userFromServer-\u003eage   = null;\n\n$result = $handler-\u003eupdate($userFromServer, ['keepNull' =\u003e false]);\nvar_dump($result);\n\n$userFromServer = $handler-\u003eget('users', $id);\nvar_dump($userFromServer);\n```\n\nThe document that is updated using the previous example must have been fetched\nfrom the server before. If you want to update a document without having fetched\nit from the server before, use `updateById()`:\n\n```php\n// update a document, identified by collection and document id\n$user        = new ArangoDocument();\n$user-\u003ename  = 'John';\n$user-\u003elikes = ['Running', 'Rowing'];\n\n// Notice that for the example we're getting the existing \n// document id via a method call. Normally we would use the known id\n$result = $handler-\u003eupdateById('users', $userFromServer-\u003egetId(), $user);\nvar_dump($result);\n\n$userFromServer = $handler-\u003eget('users', $id);\nvar_dump($userFromServer);\n```\n\n## Replace documents\n\nTo completely replace an existing document, the `replace()` method of the\n_DocumentHandler_ class can be used. In this example we want to remove the\n`state` attribute:\n\n```php\n// replace a document (notice that we are using the previously fetched document)\n// In this example we are removing the state attribute\nunset($userFromServer-\u003estate);\n\n$result = $handler-\u003ereplace($userFromServer);\nvar_dump($result);\n\n$userFromServer = $handler-\u003eget('users', $id);\nvar_dump($userFromServer);\n```\n\nThe document that is replaced using the previous example must have been fetched\nfrom the server before. If you want to replace a document without having fetched\nit from the server before, use `replaceById()`:\n\n```php\n// replace a document, identified by collection and document id\n$user        = new ArangoDocument();\n$user-\u003ename  = 'John';\n$user-\u003elikes = ['Running', 'Rowing'];\n\n// Notice that for the example we're getting the existing \n// document id via a method call. Normally we would use the known id\n$result = $handler-\u003ereplaceById('users', $userFromServer-\u003egetId(), $user);\nvar_dump($result);\n\n$userFromServer = $handler-\u003eget('users', $id);\nvar_dump($userFromServer);\n```\n\n## Delete documents\n\nTo remove an existing document on the server, the `remove()` method of the\n_DocumentHandler_ class can be used. `remove()` just needs the document to be\nremoved as a parameter:\n\n```php\n// remove a document on the server, using a document object\n$result = $handler-\u003eremove($userFromServer);\nvar_dump($result);\n```\n\nNote that the document must have been fetched from the server before. If you\nhaven't fetched the document from the server before, use the `removeById()`\nmethod. This requires just the collection name (here: _users_) and the\ndocument ID.\n\n```php\n// remove a document on the server, using a collection id and document id\n// In this example, we are using the id of the document we deleted in the previous example,\n// so it will throw an exception here. (we are catching it though, in order to continue)\n\ntry {\n    $result = $handler-\u003eremoveById('users', $userFromServer-\u003egetId());\n} catch (\\ArangoDBClient\\ServerException $e) {\n    $e-\u003egetMessage();\n}\n```\n\n## Drop collections\n\nTo drop an existing collection on the server, use the `drop()` method of the\n_CollectionHandler_ class. `drop()` just needs the name of the collection name\nto be dropped:\n\n```php\n// drop a collection on the server, using its name,\n$result = $collectionHandler-\u003edrop('users');\nvar_dump($result);\n\n// drop the other one we created, too\n$collectionHandler-\u003edrop('example');\n```\n\n## Run AQL queries\n\nTo run an AQL query, use the _Statement_ class.\n\nThe method `Statement::execute` creates a Cursor object which can be used to\niterate over the query's result set.\n\n```php\n// create a statement to insert 1000 test users\n$statement = new ArangoStatement(\n    $connection, [\n        'query' =\u003e 'FOR i IN 1..1000 INSERT { _key: CONCAT(\"test\", i) } IN users'\n    ]\n);\n\n// execute the statement\n$cursor = $statement-\u003eexecute();\n\n// now run another query on the data, using bind parameters\n$statement = new ArangoStatement(\n    $connection, [\n        'query' =\u003e 'FOR u IN @@collection FILTER u.name == @name RETURN u',\n        'bindVars' =\u003e [\n            '@collection' =\u003e 'users',\n            'name' =\u003e 'John'\n        ]\n    ]\n);\n\n// executing the statement returns a cursor\n$cursor = $statement-\u003eexecute();\n\n// easiest way to get all results returned by the cursor\nvar_dump($cursor-\u003egetAll());\n\n// to get statistics for the query, use Cursor::getExtra();\nvar_dump($cursor-\u003egetExtra());\n```\n\nNote: by default the Statement object will create a Cursor that converts each\nvalue into a Document object. This is normally the intended behavior for AQL\nqueries that return entire documents. However, an AQL query can also return\nprojections or any other data that cannot be converted into Document objects.\n\nIn order to suppress the conversion into Document objects, the Statement must be\ngiven the `_flat` attribute. This allows processing the results of arbitrary AQL\nqueries:\n\n```php\n// run an AQL query that does not return documents but scalars\n// we need to set the _flat attribute of the Statement in order for this to work\n$statement = new ArangoStatement(\n    $connection, [\n        'query' =\u003e 'FOR i IN 1..1000 RETURN i',\n        '_flat' =\u003e true\n    ]\n);\n\n// executing the statement returns a cursor\n$cursor = $statement-\u003eexecute();\n\n// easiest way to get all results returned by the cursor\n// note that now the results won't be converted into Document objects\nvar_dump($cursor-\u003egetAll());\n```\n\n## Bulk document handling\n\nThe ArangoDB-PHP driver provides a mechanism to easily fetch multiple documents\nfrom the same collection with a single request. All that needs to be provided is\nan array of document keys:\n\n```php\n$exampleCollection = new ArangoCollection();\n$exampleCollection-\u003esetName('example');\n$id = $collectionHandler-\u003ecreate($exampleCollection);\n\n// create a statement to insert 100 example documents\n$statement = new ArangoStatement(\n    $connection, [\n        'query' =\u003e 'FOR i IN 1..100 INSERT { _key: CONCAT(\"example\", i), value: i } IN example'\n    ]\n);\n$statement-\u003eexecute();\n\n// later on, we can assemble a list of document keys\n$keys = [];\nfor ($i = 1; $i \u003c= 100; ++$i) {\n    $keys[] = 'example' . $i;\n}\n// and fetch all the documents at once\n$documents = $collectionHandler-\u003elookupByKeys('example', $keys);\nvar_dump($documents);\n\n// we can also bulk-remove them:\n$result = $collectionHandler-\u003eremoveByKeys('example', $keys);\n\nvar_dump($result);\n```\n\n## Custom Document class\n\nIf you want to use custom document class you can pass its name to\n_DocumentHandler_ or _CollectionHandler_ using method `setDocumentClass`.\nRemember that Your class must extend `\\ArangoDBClient\\Document`.\n\n```php\n$ch = new CollectionHandler($connection);\n$ch-\u003esetDocumentClass('\\AppBundle\\Entity\\Product');\n$cursor = $ch-\u003eall('product'); \n// All returned documents will be \\AppBundle\\Entity\\Product instances\n\n$dh = new DocumentHandler($connection);\n$dh-\u003esetDocumentClass('\\AppBundle\\Entity\\Product');\n$product = $dh-\u003eget('products', 11231234);\n// Product will be \\AppBundle\\Entity\\Product instance\n```\n\nSee the [`examples/customDocumentClass.php`](examples/customDocumentClass.php)\nfile for more details.\n\n## Log exceptions\n\nThe driver provides a simple logging mechanism that is turned off by default.\nIf it is turned on, the driver logs all its exceptions using PHP's standard\n`error_log` mechanism. It calls PHP's `error_log()` function for this. It\ndepends on the PHP configuration if and where exceptions are logged. Please\nconsult your `php.ini` settings for further details.\n\nTo turn on exception logging in the driver, set a flag on the driver's\n_Exception_ base class, from which all driver exceptions are subclassed:\n\n```php\nuse ArangoDBClient\\Exception as ArangoException;\n\nArangoException::enableLogging();\n```\n\nTo turn logging off, call its `disableLogging` method:\n\n```php\nuse ArangoDBClient\\Exception as ArangoException;\n\nArangoException::disableLogging();\n```\n\n## Put it all together\n\nHere is the full code that combines all the pieces outlined above:\n\n```php\n// use the following line when using Composer\n// require __DIR__ . '/vendor/composer/autoload.php';\n\n// use the following line when using git\nrequire __DIR__ . '/autoload.php';\n\n// set up some aliases for less typing later\nuse ArangoDBClient\\Collection as ArangoCollection;\nuse ArangoDBClient\\CollectionHandler as ArangoCollectionHandler;\nuse ArangoDBClient\\Connection as ArangoConnection;\nuse ArangoDBClient\\ConnectionOptions as ArangoConnectionOptions;\nuse ArangoDBClient\\DocumentHandler as ArangoDocumentHandler;\nuse ArangoDBClient\\Document as ArangoDocument;\nuse ArangoDBClient\\Exception as ArangoException;\nuse ArangoDBClient\\ConnectException as ArangoConnectException;\nuse ArangoDBClient\\ClientException as ArangoClientException;\nuse ArangoDBClient\\ServerException as ArangoServerException;\nuse ArangoDBClient\\Statement as ArangoStatement;\nuse ArangoDBClient\\UpdatePolicy as ArangoUpdatePolicy;\n\n// set up some basic connection options\n$connectionOptions = [\n    // database name\n    ArangoConnectionOptions::OPTION_DATABASE =\u003e '_system',\n    // server endpoint to connect to\n    ArangoConnectionOptions::OPTION_ENDPOINT =\u003e 'tcp://127.0.0.1:8529',\n    // authorization type to use (currently supported: 'Basic')\n    ArangoConnectionOptions::OPTION_AUTH_TYPE =\u003e 'Basic',\n    // user for basic authorization\n    ArangoConnectionOptions::OPTION_AUTH_USER =\u003e 'root',\n    // password for basic authorization\n    ArangoConnectionOptions::OPTION_AUTH_PASSWD =\u003e '',\n    // connection persistence on server. can use either 'Close' (one-time connections) or 'Keep-Alive' (re-used connections)\n    ArangoConnectionOptions::OPTION_CONNECTION =\u003e 'Keep-Alive',\n    // connect timeout in seconds\n    ArangoConnectionOptions::OPTION_TIMEOUT =\u003e 3,\n    // whether or not to reconnect when a keep-alive connection has timed out on server\n    ArangoConnectionOptions::OPTION_RECONNECT =\u003e true,\n    // optionally create new collections when inserting documents\n    ArangoConnectionOptions::OPTION_CREATE =\u003e true,\n    // optionally create new collections when inserting documents\n    ArangoConnectionOptions::OPTION_UPDATE_POLICY =\u003e ArangoUpdatePolicy::LAST,\n];\n\n\n// turn on exception logging (logs to whatever PHP is configured)\nArangoException::enableLogging();\n\ntry {\n    $connection = new ArangoConnection($connectionOptions);\n\n    $collectionHandler = new ArangoCollectionHandler($connection);\n\n    // clean up first\n    if ($collectionHandler-\u003ehas('users')) {\n        $collectionHandler-\u003edrop('users');\n    }\n    if ($collectionHandler-\u003ehas('example')) {\n        $collectionHandler-\u003edrop('example');\n    }\n\n    // create a new collection\n    $userCollection = new ArangoCollection();\n    $userCollection-\u003esetName('users');\n    $id = $collectionHandler-\u003ecreate($userCollection);\n\n    // print the collection id created by the server\n    var_dump($id);\n\n    // check if the collection exists\n    $result = $collectionHandler-\u003ehas('users');\n    var_dump($result);\n\n    $handler = new ArangoDocumentHandler($connection);\n\n    // create a new document\n    $user = new ArangoDocument();\n\n    // use set method to set document properties\n    $user-\u003eset('name', 'John');\n    $user-\u003eset('age', 25);\n    $user-\u003eset('thisIsNull', null);\n\n    // use magic methods to set document properties\n    $user-\u003elikes = ['fishing', 'hiking', 'swimming'];\n\n    // send the document to the server\n    $id = $handler-\u003esave('users', $user);\n\n    // check if a document exists\n    $result = $handler-\u003ehas('users', $id);\n    var_dump($result);\n\n    // print the document id created by the server\n    var_dump($id);\n    var_dump($user-\u003egetId());\n\n\n    // get the document back from the server\n    $userFromServer = $handler-\u003eget('users', $id);\n    var_dump($userFromServer);\n\n    // get a document list back from the server, using a document example\n    $cursor = $collectionHandler-\u003ebyExample('users', ['name' =\u003e 'John']);\n    var_dump($cursor-\u003egetAll());\n\n\n    // update a document\n    $userFromServer-\u003elikes = ['fishing', 'swimming'];\n    $userFromServer-\u003estate = 'CA';\n\n    $result = $handler-\u003eupdate($userFromServer);\n    var_dump($result);\n\n    $userFromServer = $handler-\u003eget('users', $id);\n    var_dump($userFromServer);\n\n\n    // update a document removing an attribute,\n    // The 'keepNull'=\u003efalse option will cause ArangoDB to\n    // remove all attributes in the document,\n    // that have null as their value - not only the ones defined here\n\n    $userFromServer-\u003elikes = ['fishing', 'swimming'];\n    $userFromServer-\u003estate = 'CA';\n    $userFromServer-\u003eage   = null;\n\n    $result = $handler-\u003eupdate($userFromServer, ['keepNull' =\u003e false]);\n    var_dump($result);\n\n    $userFromServer = $handler-\u003eget('users', $id);\n    var_dump($userFromServer);\n\n\n    // replace a document (notice that we are using the previously fetched document)\n    // In this example we are removing the state attribute\n    unset($userFromServer-\u003estate);\n\n    $result = $handler-\u003ereplace($userFromServer);\n    var_dump($result);\n\n    $userFromServer = $handler-\u003eget('users', $id);\n    var_dump($userFromServer);\n\n\n    // replace a document, identified by collection and document id\n    $user                  = new ArangoDocument();\n    $user-\u003ename            = 'John';\n    $user-\u003elikes           = ['Running', 'Rowing'];\n    $userFromServer-\u003estate = 'CA';\n\n    // Notice that for the example we're getting the existing\n    // document id via a method call. Normally we would use the known id\n    $result = $handler-\u003ereplaceById('users', $userFromServer-\u003egetId(), $user);\n    var_dump($result);\n\n    $userFromServer = $handler-\u003eget('users', $id);\n    var_dump($userFromServer);\n\n\n    // remove a document on the server\n    $result = $handler-\u003eremove($userFromServer);\n    var_dump($result);\n\n\n    // remove a document on the server, using a collection id and document id\n    // In this example, we are using the id of the document we deleted in the previous example,\n    // so it will throw an exception here. (we are catching it though, in order to continue)\n\n    try {\n        $result = $handler-\u003eremoveById('users', $userFromServer-\u003egetId());\n    } catch (\\ArangoDBClient\\ServerException $e) {\n        $e-\u003egetMessage();\n    }\n\n\n\n    // create a statement to insert 1000 test users\n    $statement = new ArangoStatement(\n        $connection, [\n            'query' =\u003e 'FOR i IN 1..1000 INSERT { _key: CONCAT(\"test\", i) } IN users'\n        ]\n    );\n\n    // execute the statement\n    $cursor = $statement-\u003eexecute();\n\n\n    // now run another query on the data, using bind parameters\n    $statement = new ArangoStatement(\n        $connection, [\n            'query' =\u003e 'FOR u IN @@collection FILTER u.name == @name RETURN u',\n            'bindVars' =\u003e [\n                '@collection' =\u003e 'users',\n                'name' =\u003e 'John'\n            ]\n        ]\n    );\n\n    // executing the statement returns a cursor\n    $cursor = $statement-\u003eexecute();\n\n    // easiest way to get all results returned by the cursor\n    var_dump($cursor-\u003egetAll());\n\n    // to get statistics for the query, use Cursor::getExtra();\n    var_dump($cursor-\u003egetExtra());\n\n\n    $exampleCollection = new ArangoCollection();\n    $exampleCollection-\u003esetName('example');\n    $id = $collectionHandler-\u003ecreate($exampleCollection);\n\n    // create a statement to insert 100 example documents\n    $statement = new ArangoStatement(\n        $connection, [\n            'query' =\u003e 'FOR i IN 1..100 INSERT { _key: CONCAT(\"example\", i), value: i } IN example'\n        ]\n    );\n    $statement-\u003eexecute();\n\n    // later on, we can assemble a list of document keys\n    $keys = [];\n    for ($i = 1; $i \u003c= 100; ++$i) {\n        $keys[] = 'example' . $i;\n    }\n    // and fetch all the documents at once\n    $documents = $collectionHandler-\u003elookupByKeys('example', $keys);\n    var_dump($documents);\n\n    // we can also bulk-remove them:\n    $result = $collectionHandler-\u003eremoveByKeys('example', $keys);\n\n    var_dump($result);\n\n\n    // drop a collection on the server, using its name,\n    $result = $collectionHandler-\u003edrop('users');\n    var_dump($result);\n\n    // drop the other one we created, too\n    $collectionHandler-\u003edrop('example');\n} catch (ArangoConnectException $e) {\n    print 'Connection error: ' . $e-\u003egetMessage() . PHP_EOL;\n} catch (ArangoClientException $e) {\n    print 'Client error: ' . $e-\u003egetMessage() . PHP_EOL;\n} catch (ArangoServerException $e) {\n    print 'Server error: ' . $e-\u003egetServerCode() . ': ' . $e-\u003egetServerMessage() . ' - ' . $e-\u003egetMessage() . PHP_EOL;\n}\n```\n\n## More information\n\n- More example code, containing some code to create, delete and rename\n  collections, is provided in the [`examples`](examples) subdirectory that is\n  provided with the library.\n\n- [PHPDoc documentation](http://arangodb.github.io/arangodb-php/)\n  for the complete library\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farangodb%2Farangodb-php","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Farangodb%2Farangodb-php","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Farangodb%2Farangodb-php/lists"}