PHPackages                             stefanak-michal/bolt - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. stefanak-michal/bolt

ActiveLibrary[Database &amp; ORM](/categories/database)

stefanak-michal/bolt
====================

PHP library to provide connectivity to graph database over TCP socket with Bolt specification

v7.4.0(2mo ago)79655.8k—3.9%11[4 issues](https://github.com/stefanak-michal/php-bolt-driver/issues)7MITPHPPHP ^8.1

Since Mar 16Pushed 2mo ago7 watchersCompare

[ Source](https://github.com/stefanak-michal/php-bolt-driver)[ Packagist](https://packagist.org/packages/stefanak-michal/bolt)[ Docs](https://github.com/stefanak-michal/php-bolt-driver)[ Fund](https://ko-fi.com/michalstefanak)[ RSS](/packages/stefanak-michal-bolt/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (66)Used By (7)

[![Logo](https://repository-images.githubusercontent.com/198229221/9de925f4-668f-4f65-a9d0-e989db6d4fe3)](https://repository-images.githubusercontent.com/198229221/9de925f4-668f-4f65-a9d0-e989db6d4fe3)

Bolt
====

[](#bolt)

PHP library for communication with graph database over TCP socket with Bolt protocol specification. Bolt protocol was created by [Neo4j](https://neo4j.com/) and documentation is available at [https://www.neo4j.com/](https://www.neo4j.com/docs/bolt/current/). This library is aimed to be low level, support all available versions and keep up with protocol messages architecture and specifications.

[![Ask DeepWiki](https://camo.githubusercontent.com/0f5ae213ac378635adeb5d7f13cef055ad2f7d9a47b36de7b1c67dbe09f609ca/68747470733a2f2f6465657077696b692e636f6d2f62616467652e737667)](https://deepwiki.com/stefanak-michal/php-bolt-driver)[![](https://camo.githubusercontent.com/cd4e4be3ded8ee7512adeb11070717e35f2e795348a555b18b2cbe0c1dba1eee/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73746566616e616b2d6d696368616c2f626f6c74)](https://packagist.org/packages/stefanak-michal/bolt/stats)[![](https://camo.githubusercontent.com/37616e478227710948db03cee1e52eb43a86e56fd74dfc3ad380c62becf3c914/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f73746566616e616b2d6d696368616c2f626f6c74)](https://github.com/neo4j-php/Bolt/releases)[![](https://camo.githubusercontent.com/8772b21eea49996a5f1048512cb71c1c0af594838971c1b1737bc54b2af0b30a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f636f6d6d6974732d73696e63652f73746566616e616b2d6d696368616c2f626f6c742f6c6174657374)](https://github.com/neo4j-php/Bolt/releases/latest)[![](https://camo.githubusercontent.com/351e04e73f92a5b467ee5462896588467088445dcc619f012431e7cb7a1dbd8c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f73746566616e616b2d6d696368616c2f426f6c74)](https://github.com/neo4j-php/Bolt/stargazers)

[![ko-fi](https://camo.githubusercontent.com/201ef269611db7eb6b5d08e9f756ab8980df3014b64492770bdf13a6ed924641/68747470733a2f2f6b6f2d66692e636f6d2f696d672f676974687562627574746f6e5f736d2e737667)](https://ko-fi.com/Z8Z5ABMLW)

[![image](https://private-user-images.githubusercontent.com/5502917/533897326-5d74f0e4-23e5-467b-a68c-7dbe9a49de3c.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzQzNDUzOTUsIm5iZiI6MTc3NDM0NTA5NSwicGF0aCI6Ii81NTAyOTE3LzUzMzg5NzMyNi01ZDc0ZjBlNC0yM2U1LTQ2N2ItYTY4Yy03ZGJlOWE0OWRlM2MucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI2MDMyNCUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNjAzMjRUMDkzODE1WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9NGU0OTdkZjRiMjZlZDBmM2MzOWI0MzY2NjdkNDk1ZjQ3NDExNTNhMjljZDA3N2ZhY2I1ZjM2NGJhYjg5Yjc1ZCZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QifQ.BPp69G54RVRkLhNmdvw1u9M-YOCPVrODDmJIPMe81Lg)](https://awsmfoss.com/neo4j-bolt-php/)

🏢 Professional Support and Consulting
-------------------------------------

[](#office-professional-support-and-consulting)

Need help with integrating communication with graph databases in your PHP project? I offer professional support and consulting services related to graph databases.

My services include:

- Integration assistance
- Performance tuning
- Custom development
- Training

Website:

🏷️ Version support
------------------

[](#label-version-support)

We are trying to keep up and this library supports **Bolt &lt;= 6**.

📚 Supported ecosystems
----------------------

[](#books-supported-ecosystems)

- Neo4j [bolt compatibility](https://www.neo4j.com/docs/bolt/current/bolt-compatibility/)
- Memgraph [bolt compatibility](https://memgraph.com/docs/client-libraries)
- Amazon Neptune [bolt compatiblity](https://docs.aws.amazon.com/neptune/latest/userguide/access-graph-opencypher-bolt.html#access-graph-opencypher-bolt-connections)
- LadybugDB with wrapper [bolt4rs](https://github.com/LadybugDB/bolt4rs)
- [DozerDB](https://dozerdb.org/)
- [ONgDB](https://graphfoundation.org/ongdb/)
- [NornicDB](https://github.com/orneryd/NornicDB)

✅ Requirements
--------------

[](#white_check_mark-requirements)

This library keep up with [PHP supported versions](https://www.php.net/supported-versions.php) what means it is at **PHP^8.1**.

### PHP Extensions

[](#php-extensions)

- [mbstring](https://www.php.net/manual/en/book.mbstring.php)
- [sockets](https://www.php.net/manual/en/book.sockets.php) (optional) - Required when you use Socket connection class
- [openssl](https://www.php.net/manual/en/book.openssl.php) (optional) - Required when you use StreamSocket connection class with enabled SSL

💾 Installation
--------------

[](#floppy_disk-installation)

You can use composer or download this repository from github and manually implement it.

### Composer

[](#composer)

Run the following command in your project to install the latest applicable version of the package:

`composer require stefanak-michal/bolt`

[Packagist](https://packagist.org/packages/stefanak-michal/bolt)

### Manual

[](#manual)

1. Download source code from [github](https://github.com/stefanak-michal/php-bolt-driver/)
2. Unpack
3. Copy content of `src` directory into your project

🖥️ Usage
--------

[](#desktop_computer-usage)

Concept of usage is based on Bolt messages. Bolt messages are mapped 1:1 as protocol methods. Available protocol methods depends on Bolt version. Communication works in [pipeline](https://www.neo4j.com/docs/bolt/current/bolt/message/#pipelining) and you can chain multiple Bolt messages before consuming response from the server.

Main `Bolt` class serves as Factory design pattern and it returns instance of protocol class by requested Bolt version. Basic usage consist of query execution and fetching response which is split in two methods. First message `run` is for sending queries. Second message `pull` is for fetching response from executed query on database. Response from database for Bolt message `pull` always contains n+1 rows because last entry is `success` message with meta informations.

ℹ️ More info about available Bolt messages:

### Available methods

[](#available-methods)

**Bolt class**

Method / PropertyDescriptionTypeParametersReturn\_\_constructBolt constructorpublicIConnection $connectionBoltsetProtocolVersionsSet allowed protocol versions for connectionpublicint/float/string ...$vBoltsetPackStreamVersionSet PackStream versionpublicint $version = 1BoltbuildCreate protocol instance. Method creates connection, executes handshake and do a version request.publicAProtocol$debugPrint binary communication (as hex)public staticbool**Protocol class**

Method / PropertyDescriptionParametershelloConnect to databasearray $extralogonPerform authentificationarray $authlogoffLog out authentificated userrunExecute query. Response from database are meta informations.string $statement
array $parameters = \[\]
array $extra = \[\]pullPull result from executed queryarray $extra = \[\]discardDiscard result waiting for pullarray $extra = \[\]beginStart transactionarray $extra = \[\]commitCommit transactionrollbackRollback transactionresetSend message to reset connectiontelemetryint $apigetVersionGet used protocol versiongetResponseGet waiting response from servergetResponsesGet waiting responses from serverinit@see hellopullAll@see pulldiscardAll@see discardMultiple methods accept argument called `$extra`. This argument can contain any of key-value by Bolt specification. This argument was extended during Neo4j development which means the content of it changed. You should keep in mind what version you are working with when using this argument. You can read more about extra parameter in Bolt documentation where you can look into your version and bolt message.

ℹ️ Annotation of methods in protocol classes contains direct link to specific version and message from mentioned documentation website.

### Authentication

[](#authentication)

Method logon expects `$auth` array. This array has to contain up to these three keys: scheme, principal and credentials. It depends on chosen scheme, as content for the other keys. Look at following table to choose the right structure.

schemeprincipalcredentialsnonebasicusernamepasswordbearertokenkerberostoken### Transactions

[](#transactions)

Bolt from version 3 supports transactions and protocol contains these methods:

- begin
- commit
- rollback

*`run` executes query in auto-commit transaction if explicit transaction was not open.*

### Cypher query parameters

[](#cypher-query-parameters)

Neo4jPHPNullnullBooleanbooleanIntegerintegerFloatfloatBytes[Bytes class](https://github.com/stefanak-michal/php-bolt-driver/blob/master/src/packstream/Bytes.php)StringstringListarray with consecutive numeric keys from 0Dictionaryobject or array which is not considered as listStructureClasses implementing `IStructure` by protocol version ([docs](https://www.neo4j.com/docs/bolt/current/bolt/structure-semantics/))List or dictionary can be also provided as instance of class implementing `Bolt\packstream\IPackListGenerator`or `Bolt\PackStream\IPackDictionaryGenerator`. This approach helps with memory management while working with big amount of data. To learn more you can check [performance test](https://github.com/neo4j-php/Bolt/blob/master/tests/PerformanceTest.php)or [packer test](https://github.com/neo4j-php/Bolt/blob/master/tests/PackStream/v1/PackerTest.php).

⚠️ Structures `Node`, `Relationship`, `UnboundRelationship` and `Path` cannot be used as parameter. They are available only as received data from database.

### Example

[](#example)

```
// Choose and create connection class and specify target host and port.
$conn = new \Bolt\connection\Socket('127.0.0.1', 7687);
// Create new Bolt instance and provide connection object.
$bolt = new \Bolt\Bolt($conn);
// If needed set requested protocol versions ..you can add up to 4 versions
$bolt->setProtocolVersions(5.4);
// Build and get protocol version instance which creates connection and executes handshake.
$protocol = $bolt->build();

// Initialize communication with database
$response = $protocol->hello()->getResponse();
// verify $response for successful initialization

// Login into database
$response = $protocol->logon(['scheme' => 'basic', 'principal' => 'neo4j', 'credentials' => 'neo4j'])->getResponse();
// verify $response for successful login

// Pipeline two messages. One to execute query with parameters and second to pull records.
$protocol
    ->run('RETURN $a AS num, $b AS str', ['a' => 123, 'b' => 'text'])
    ->pull();

// Fetch waiting server responses for pipelined messages.
foreach ($protocol->getResponses() as $response) {
    // $response is instance of \Bolt\protocol\Response.
    // First response is SUCCESS message for RUN message.
    // Second response is RECORD message for PULL message.
    // Third response is SUCCESS message for PULL message.
}
```

ℹ️ Default settings for bolt protocol version is 4.3, 4.4, 5.0 to 5.8 and 6. If you are within this list you can ommit calling `$bolt->setProtocolVersions();`.

### Autoload

[](#autoload)

Directory `src` contains autoload file which accepts only Bolt library namespaces. Main Bolt namespace points to this directory. If you have installed this project with composer, you have to load `vendor/autoload.php`.

### Client helper class

[](#client-helper-class)

Library contains helper class `\Bolt\helpers\Client` for simplified interaction with a graph database. It wraps common operations (authentication, queries, and transactions) into a convenient object so you don't have to manage protocol messages and responses manually.

**Constructor**

```
new \Bolt\helpers\Client(
    AProtocol $protocol,
    array $auth = ['scheme' => 'none'],
    ?Closure $logHandler = null,
    ?Closure $errorHandler = null
)
```

Authentication is performed automatically in the constructor based on the Bolt protocol version in use.

- `$protocol` — Protocol instance obtained via `Bolt::build()`.
- `$auth` — Authentication parameters (see [Authentication](#authentication)). Defaults to `['scheme' => 'none']`.
- `$logHandler` — Optional `Closure(string $query, array $params, array $stats): void` called after every action.
- `$errorHandler` — Optional `Closure(Exception $e): void`. If not set, exceptions are thrown normally.

**Methods**

MethodDescriptionReturn`query(string $query, array $params = [], array $extra = [])`Execute a query and return all rows as an array of associative arrays.`array``queryFirstField(string $query, array $params = [], array $extra = [])`Execute a query and return the first value from the first row.`mixed``queryFirstColumn(string $query, array $params = [], array $extra = [])`Execute a query and return the first column values from all rows.`array``begin(array $extra = [])`Begin a transaction. Returns `false` for Bolt &lt; 3.`bool``commit()`Commit the current transaction. Returns `false` for Bolt &lt; 3.`bool``rollback()`Rollback the current transaction. Returns `false` for Bolt &lt; 3.`bool``getStatistics()`Return statistics from the last executed query (keys depend on the database). Always includes a `rows` key with the result row count.`array`**Example**

```
$conn = new \Bolt\connection\Socket('127.0.0.1', 7687);
$bolt = new \Bolt\Bolt($conn);
$protocol = $bolt->build();

$client = new \Bolt\helpers\Client(
    $protocol,
    ['scheme' => 'basic', 'principal' => 'neo4j', 'credentials' => 'neo4j'],
    function (string $query, array $params, array $stats): void {
        // optional: log every executed query
        error_log($query);
    },
    function (Exception $e): void {
        // optional: handle exceptions; if omitted they are thrown normally
        error_log($e->getMessage());
    }
);

// Returns all rows as associative arrays keyed by field name
$rows = $client->query('MATCH (n:Person) RETURN n.name AS name, n.age AS age');
// $rows = [['name' => 'Alice', 'age' => 30], ['name' => 'Bob', 'age' => 25]]

// Returns only the first value from the first row
$name = $client->queryFirstField('MATCH (n:Person) RETURN n.name LIMIT 1');

// Returns the first column value from every row
$names = $client->queryFirstColumn('MATCH (n:Person) RETURN n.name');

// Transaction example
$client->begin();
$client->query('CREATE (n:Person {name: $name})', ['name' => 'Charlie']);
$client->commit(); // or $client->rollback()

// Statistics from the last executed query
$stats = $client->getStatistics();
// e.g. ['nodes-created' => 1, 'rows' => 0]
```

⛓️ Connection
-------------

[](#chains-connection)

Bolt class constructor accepts connection argument. This argument has to be instance of class which implements IConnection interface. Library offers few options.

**\\Bolt\\connection\\Socket**

This class use php extension sockets and has better memory usage. More informations here:

**\\Bolt\\connection\\StreamSocket**

This class uses php stream functions. Which is a part of php and there is no extensions needed. More informations here:

StreamSocket besides of implemented methods from interface has method to configure SSL. SSL option requires php extension openssl. When you want to activate SSL you have to call method `setSslContextOptions`. This method accept array by php specification available here: .

**\\Bolt\\connection\\PStreamSocket**

This class extends StreamSocket and adds support for persistent connections. Upon reuse of connection remaining buffer is consumed and message RESET is automatically sent. PHP is stateless therefore using this connection class requires storing meta information about active TCP connection. These informations are stored in [PSR-16 cache](#minidisc-psr-16-cache).

⚠️ If your system reuse persistent connection and meta information about it was lost for some reason, your attempt to connect will end with ConnectionTimeoutException. Repeated attempt to connect will succeed.

🔒 SSL
-----

[](#lock-ssl)

Connection secured with SSL is available only with connection classes `StreamSocket` and `PStreamSocket`.

### Neo4j Aura

[](#neo4j-aura)

Connecting to Aura requires encrypted connection by default. To connect to Aura you have to use connection class with SSL support and enable SSL.

```
$conn = new \Bolt\connection\StreamSocket('helloworld.databases.neo4j.io');
// enable SSL
$conn->setSslContextOptions();
$bolt = new \Bolt\Bolt($conn);
```

*For more informations about what argument can be passed to `setSslContextOptions` check out [php.net](https://www.php.net/manual/en/context.ssl.php)*

### Example on localhost database with self-signed certificate:

[](#example-on-localhost-database-with-self-signed-certificate)

```
$conn = new \Bolt\connection\StreamSocket();
$conn->setSslContextOptions([
    'local_cert'=> 'd:\www\bolt\cert\public_cert.pem',
    'local_pk' => 'd:\www\bolt\cert\private_key.pem',
    'passphrase' => 'password',
    'allow_self_signed' => true,
    'verify_peer' => false,
    'verify_peer_name' => false
]);
$bolt = new \Bolt\Bolt($conn);
```

🔖 You can also take a look at my article on how to implement SSL for Neo4j running on localhost at [Neo4j and self signed certificate](https://ko-fi.com/post/Neo4j-and-self-signed-certificate-on-Windows-S6S2I0KQT).

⏱️ Timeout
----------

[](#stopwatch-timeout)

Connection class constructor contains `$timeout` argument. This timeout is for established socket connection. To set up timeout for establishing socket connection itself you have to set ini directive `default_socket_timeout`.

*Setting up ini directive isn't part of connection class because function `ini_set` can be disabled on production environments for security reasons.*

🚦 Server state
--------------

[](#vertical_traffic_light-server-state)

Server state is not reported by server but it is evaluated by received response. You can access current state through property `$protocol->serverState`. This property is updated with every call `getResponse(s)`.

💽 PSR-16 cache
--------------

[](#minidisc-psr-16-cache)

This library contains own PSR-16 cache implementation `\Bolt\helpers\FileCache`. It stores files in temporary directory. Obtaining cache instance throughout the project is secured with `\Bolt\helpers\CacheProvider::get()`. You can set own implementation by calling `\Bolt\helpers\CacheProvider::set($cache)`.

[PSR-16 specification](https://www.php-fig.org/psr/psr-16/)

📊 Analytics
-----------

[](#bar_chart-analytics)

Bolt does collect anonymous analytics data. These data are just aggregated counts of executed queries and sessions. They are stored in [cache](#minidisc-psr-16-cache) and submitted once a day after midnight. You can opt out with environment variable `BOLT_ANALYTICS_OPTOUT`.

Analytics data are public and available at [Mixpanel](https://eu.mixpanel.com/p/7ttVKqvjdqJtGCjLCFgdeC).

###  Health Score

65

—

FairBetter than 99% of packages

Maintenance86

Actively maintained with recent releases

Popularity52

Moderate usage in the ecosystem

Community27

Small or concentrated contributor base

Maturity79

Established project with proven stability

 Bus Factor1

Top contributor holds 89.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~35 days

Recently: every ~60 days

Total

62

Last Release

64d ago

Major Versions

v3.1.3 → v4.12022-07-11

v3.1.4 → v4.1.12022-07-19

v4.1.1 → v5.0.02022-11-06

v5.1.1 → v6.0.02022-12-02

v6.1.4 → v7.0.02023-12-18

PHP version history (5 changes)v1.0.2PHP &gt;=7.1.0

v4.0.0PHP &gt;=7.4

v6.0.0PHP &gt;=8

v6.0.2PHP ^8

v7.0.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/04e29b3719023eae810d2f457310ac2f7deb64314e53795ca135dafd505ce4b2?d=identicon)[oLDo](/maintainers/oLDo)

---

Top Contributors

[![stefanak-michal](https://avatars.githubusercontent.com/u/5502917?v=4)](https://github.com/stefanak-michal "stefanak-michal (547 commits)")[![transistive](https://avatars.githubusercontent.com/u/16435930?v=4)](https://github.com/transistive "transistive (56 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (3 commits)")[![jonathan-rowley](https://avatars.githubusercontent.com/u/50716090?v=4)](https://github.com/jonathan-rowley "jonathan-rowley (2 commits)")[![luutruong](https://avatars.githubusercontent.com/u/3833024?v=4)](https://github.com/luutruong "luutruong (2 commits)")[![tomswinkels](https://avatars.githubusercontent.com/u/9036151?v=4)](https://github.com/tomswinkels "tomswinkels (2 commits)")

---

Tags

boltbolt-protocoldrivergraph-databasesmemgraphneo4jnodes-2022phpdatabasetcpSocketdriverneo4jgraphboltmemgraph

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/stefanak-michal-bolt/health.svg)

```
[![Health](https://phpackages.com/badges/stefanak-michal-bolt/health.svg)](https://phpackages.com/packages/stefanak-michal-bolt)
```

###  Alternatives

[laudis/neo4j-php-client

Neo4j-PHP-Client is the most advanced PHP Client for Neo4j

184616.9k31](/packages/laudis-neo4j-php-client)[vinelab/neoeloquent

Laravel wrapper for the Neo4j graph database REST interface

65393.1k1](/packages/vinelab-neoeloquent)[graphaware/neo4j-common

Common Utilities library for Neo4j

24876.2k24](/packages/graphaware-neo4j-common)[neo4j/neo4j-bundle

Symfony integration for Neo4j

8272.1k](/packages/neo4j-neo4j-bundle)[ulobby/neoeloquent

Laravel wrapper for the Neo4j graph database REST interface

4473.4k](/packages/ulobby-neoeloquent)[laravel-freelancer-nl/aranguent

Laravel bridge for the ArangoDB Multi-model database

517.0k](/packages/laravel-freelancer-nl-aranguent)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
