百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
N

neo4j-php-client

> 数据库
开源

用于 neo4j 数据库的 PHP 客户端和驱动

187 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

用于 neo4j 数据库的 PHP 客户端和驱动

Neo4j PHP Client and Driver

Control to worlds' most powerful graph database

  • Pick and choose your drivers with easy configuration
  • Intuitive API
  • Extensible
  • Designed, built and tested under close supervision with the official neo4j driver team
  • Validated with testkit
  • Fully typed with psalm
  • Bolt and Neo4j (auto-routed) drivers available

See the driver in action

  • An implementation of the class movie database. It uses Slim and neo4j-php-client to build an API for the classic movie's example of neo4j.
  • An complete implementation of the realworld example. It uses Laravel to implement the real world example project, the mother of all demo apps.
  • The friends api for the world's most corny example project leveraging the power of Neo4j.

For some more detailed write-ups you can refer to these blogposts:

  • How to build a JSON RESTful API with Neo4j, PHP and Open API
  • Building a Web App with Neo4j, AuraDB and PHP
  • Connect to Neo4j with PHP
  • Enterprise level PHP and Neo4j

Or watch any of these videos.

Start your driving experience in three easy steps

Step 1: install via composer

bash
composer require laudis/neo4j-php-client

Find more details here

Step 2: create a client

php
use Laudis\Neo4j\Authentication\Authenticate;
use Laudis\Neo4j\ClientBuilder;

$client = ClientBuilder::create()
    ->withDriver('bolt', 'bolt+s://user:password@localhost') // creates a bolt driver
    ->withDriver('neo4j', 'neo4j://neo4j.test.com?database=my-database', Authenticate::oidc('token')) // creates an auto routed driver with an OpenID Connect token
    ->withDefaultDriver('bolt')
    ->build();

You have now created a client with bolt and neo4j drivers. The default driver that the client will use is bolt.

Note: The HTTP/HTTPS drivers were removed in version 3.3.0. Use Bolt (bolt://, bolt+s://, …) or Neo4j (neo4j://, …) URIs only.

Read more about the URLs and how to use them to configure drivers here.

Step 3: run a transaction

php
use Laudis\Neo4j\Contracts\TransactionInterface;

$result = $client->writeTransaction(static function (TransactionInterface $tsx) {
    $result = $tsx->run('MERGE (x {y: "z"}:X) return x');
    return $result->first()->get('x')['y'];
});

echo $result; // echos 'z'

Decide how to send your Cypher queries

You can control the driver using three different approaches:

  • Auto committed queries (easiest and most intuitive)
  • Transaction functions (most portable)
  • Unmanaged transactions (for the highest degree of control)

Auto committed queries

Auto committed queries are the most straightforward and most intuitive but have many drawbacks when running complex business logic or within a high availability environment.

Run a simple cypher query

php
$client->run(
    'MERGE (user {email: $email})', //The query is a required parameter
    ['email' => '[email protected]'],  //Requests can be optionally added
    'backup' //The default connection can be overridden
);

Run a statement object:

php
use Laudis\Neo4j\Databags\Statement;

$statement = new Statement('MERGE (user {email: $email})', ['email' => '[email protected]']);
$client->runStatement($statement, 'default');

Transaction functions

Transaction functions are the de facto standard when using the driver. It is the most portable as it is resistant to a lot of the pitfalls when first developing with high availability solutions such as Neo4j aura or a cluster.

The driver manages transaction functions:

  • It re-executes the function in case of a transient error.
  • It commits the transaction on successful execution
  • It rolls back the transaction in case of a timeout.
  • It routes the execution to a relevant follower or leader server when the neo4j protocol is enabled.

ATTENTION: Because of the automatic retry functionality, the function should produce the same result on subsequent recalls, or in more technical terms: should be idempotent. Always remember this when designing the execution logic within the function.

Some examples:

…

Unmanaged transactions

If you need lower-level access to the drivers' capabilities, then you want unmanaged transactions. They allow for completely controllable commits and rollbacks.

Opening a transaction

The beginTransaction method will start a transaction with the relevant driver.

php
use Laudis\Neo4j\Databags\Statement;

$tsx = $client->beginTransaction(
    // This is an optional set of statements to execute while opening the transaction
    [Statement::create('MERGE (x:Person({email: $email})', ['email' => '[email protected]'])],
    'backup' // This is the optional connection alias
);

Note that beginTransaction only returns the transaction object, not the results of the provided statements.

Running statements within a transaction

The transaction can run statements just like the client object as long as it is still open.

php
$result = $tsx->run('MATCH (x) RETURN x LIMIT 100');
$result = $tsx->runStatement(Statement::create('MATCH (x) RETURN x LIMIT 100'));
$results = $tsx->runStatements([Statement::create('MATCH (x) RETURN x LIMIT 100')]);

Finish a transaction

Rollback a transaction:

php
$tsx->rollback();

Commit a transaction:

php
$tsx->commit([Statement::create('MATCH (x) RETURN x LIMIT 100')]);

Accessing the results

Results are returned in a standard format of rows and columns:

php
// Results are a CypherList
$results = $client->run('MATCH (node:Node) RETURN node, node.id AS id');

// A row is a CypherMap
foreach ($results as $result) {
    // Returns a Node
    $node = $result->get('node');

    echo $node->getProperty('id');
    echo $result->get('id');
}

Cypher values and types map to these php types and classes:

Cypher Php
null * null
string * string
integer * int
float * float
boolean * bool
Map * \Laudis\Neo4j\Types\CypherMap
List * \Laudis\Neo4j\Types\CypherList
Point * \Laudis\Neo4j\Contracts\PointInterface **
Date * \Laudis\Neo4j\Types\Date
Time * \Laudis\Neo4j\Types\Time
LocalTime * \Laudis\Neo4j\Types\LocalTime
DateTime * \Laudis\Neo4j\Types\DateTime
DateTimeZoneId * \Laudis\Neo4j\Types\DateTimeZoneId
LocalDateTime * \Laudis\Neo4j\Types\LocalDateTime
Duration * \Laudis\Neo4j\Types\Duration
Node \Laudis\Neo4j\Types\Node
Relationship \Laudis\Neo4j\Types\Relationship
Path \Laudis\Neo4j\Types\Path
Vector \Laudis\Neo4j\Types\Vector ***

(*) These items can also be used as parameters in the bolt protocol and will automatically be converted by the driver, so they can be used in Cypher.

(***) Vector (e.g. embedding) is only produced when decoding results from the server; it is not supported as a query parameter.

Besides these examples, \DateTimeInterface will map to DateTimeZoneId in Cypher. An empty or list-type array will be converted to a cypher List, and an associative array will be converted to a map.

(**) A point can be one of four types implementing PointInterface: \Laudis\Neo4j\Types\CartesianPoint \Laudis\Neo4j\Types\Cartesian3DPoint \Laudis\Neo4j\Types\WGS84Point \Laudis\Neo4j\Types\WGS843DPoint

Diving Deeper

Differentiating between parameter type

Cypher has lists and maps. This notion can be problematic as the standard php arrays encapsulate both. When you provide an empty array as a parameter, it will be impossible to determine an empty list or map.

The ParameterHelper class is the ideal companion for this:

php
use Laudis\Neo4j\ParameterHelper;

$client->run('MATCH (x) WHERE x.slug in $listOrMap RETURN x', ['listOrMap' => ParameterHelper::asList([])]); // will return an empty CypherList
$client->run('MATCH (x) WHERE x.slug in $listOrMap RETURN x', ['listOrMap' => ParameterHelper::asMap([])]); // will error
$client->run('MATCH (x) WHERE x.slug in $listOrMap RETURN x', ['listOrMap' => []]); // will return an empty CypherList

Version compatibility matrix

Driver Version PHP Version Neo4j Version
^2.8 7.4, ^8.0 ^3.5, ^4.0
^3.0 ^8.0 ^4.0, ^5.0

Neo4j Feature Support

Feature Supported?
Authentication Yes
Transactions Yes
Bolt Protocol Yes
Cluster Yes
Aura Yes
Jolt Protocol Yes
Bookmarks Yes

In-depth requirements

  • PHP >= 7.4
  • A Neo4j database (minimum version 3.5)
  • ext-bcmath
  • ext-json
  • ext-sockets

Result formats/hydration

In order to make the results of the Bolt protocol uniform, the driver provides and summarizes the results.

The default formatter is the \Laudis\Neo4j\Formatters\SummarizedResultFormatter, which is explained extensively in the result format section.

\Laudis\Neo4j\Formatter\SummarizedResultFormatter adds an extensive result summary.

The client builder provides an easy way to change the formatter:

…

Concepts

The driver API described here is the main target of the driver. Because of this, the client is nothing more than a driver manager. The driver creates sessions. A session runs queries through a transaction.

Because of this behaviour, you can access each concept starting from the client like this:

…

If you need complete control, you can control each object with custom configuration objects.

Client

A client manages drivers and routes the queries to the correct drivers based on preconfigured aliases.

Driver

The driver object is the thread-safe backbone that gives access to Neo4j. It owns a connection pool and can spawn sessions for carrying out work.

php
use Laudis\Neo4j\Basic\Driver;
use Laudis\Neo4j\Databags\DriverConfiguration;

$driver = Driver::create(
    uri: 'neo4j://user:mypassword@Localhost:7687',
    configuration: DriverConfiguration::create()->wi

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

PHPboltconnectiondatabasedriver

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库