자세한 내용은 다음과 같은 블로그 게시물을 참조 할 수 있습니다.
또는이 비디오를보십시오.
composer require laudis/neo4j-php-client자세한 내용은 여기를 참조하십시오
use Laudis Neo4j Authentication Authenticate ;
use Laudis Neo4j ClientBuilder ;
$ client = ClientBuilder:: create ()
-> withDriver ( ' bolt ' , ' bolt+s://user:password@localhost ' ) // creates a bolt driver
-> withDriver ( ' https ' , ' https://test.com ' , Authenticate:: basic ( ' user ' , ' password ' )) // creates an http 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 ();이제 Bolt, HTTPS 및 NEO4J 드라이버 로 클라이언트를 만들었습니다. 클라이언트가 사용할 기본 드라이버는 볼트 입니다.
URL에 대한 자세한 내용과 여기에서 드라이버를 구성하는 방법을 읽으십시오.
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' 세 가지 다른 접근법을 사용하여 드라이버를 제어 할 수 있습니다.
Auto Commited Queries는 가장 간단하고 직관적이지만 복잡한 비즈니스 논리를 실행할 때 또는 고 가용성 환경 내에서 많은 단점이 있습니다.
$ 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
); use Laudis Neo4j Databags Statement ;
$ statement = new Statement ( ' MERGE (user {email: $email}) ' , [ ' email ' => ' [email protected] ' ]);
$ client -> runStatement ( $ statement , ' default ' ); runStatements 메소드는 모든 문을 한 번에 실행합니다. 이 방법은 특히 HTTP 프로토콜을 사용할 때 데이터베이스 호출 수를 줄이는 데 필수적인 도구입니다.
use Laudis Neo4j Databags Statement ;
$ results = $ client -> runStatements ([
Statement:: create ( ' MATCH (x) RETURN x LIMIT 100 ' ),
Statement:: create ( ' MERGE (x:Person {email: $email}) ' , [ ' email ' => ' [email protected] ' ])
]);트랜잭션 기능은 드라이버를 사용할 때 사실상 표준입니다. Neo4J Aura 또는 클러스터와 같은 고 가용성 솔루션으로 처음 개발할 때 많은 함정에 저항력이 있기 때문에 가장 휴대용입니다.
드라이버는 거래 기능을 관리합니다.
주의 : 자동 재 시도 기능으로 인해 기능은 후속 리콜 또는보다 기술적 인 용어에서 동일한 결과를 생성해야합니다. 함수 내에서 실행 로직을 설계 할 때 항상 이것을 기억하십시오.
몇 가지 예 :
use Laudis Neo4j Contracts TransactionInterface ;
// Do a simple merge and return the result
$ result = $ client -> writeTransaction ( static function ( TransactionInterface $ tsx ) {
$ result = $ tsx -> run ( ' MERGE (x {y: "z"}:X) return x ' );
return $ result -> first ()-> get ( ' x ' )[ ' y ' ];
});
// Will result in an error
$ client -> readTransaction ( static function ( TransactionInterface $ tsx ) {
$ tsx -> run ( ' MERGE (x {y: "z"}:X) return x ' );
});
// This is a poorly designed transaction function
$ client -> writeTransaction ( static function ( TransactionInterface $ tsx ) use ( $ externalCounter ) {
$ externalCounter -> incrementNodesCreated ();
$ tsx -> run ( ' MERGE (x {y: $id}:X) return x ' , [ ' id ' => Uuid:: v4 ()]);
});
// This achieves the same effect but is safe in case it should be retried. The function is now idempotent.
$ id = Uuid:: v4 ();
$ client -> writeTransaction ( static function ( TransactionInterface $ tsx ) use ( $ id ) {
$ tsx -> run ( ' MERGE (x {y: $id}:X) return x ' , [ ' id ' => $ id ]);
});
$ externalCounter -> incrementNodesCreated ();드라이버 기능에 대한 수준의 액세스가 필요한 경우 관리되지 않는 트랜잭션을 원합니다. 그들은 완전히 제어 가능한 커밋과 롤백을 허용합니다.
beginTransaction 메소드는 관련 드라이버와의 트랜잭션을 시작합니다.
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
);
beginTransaction은 제공된 명령문의 결과가 아니라 트랜잭션 객체 만 반환합니다.
트랜잭션은 여전히 열려있는 한 클라이언트 객체와 마찬가지로 명령문을 실행할 수 있습니다.
$ 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 ' )]);거래 롤백 거래 :
$ tsx -> rollback ();거래 커밋 :
$ tsx -> commit ([Statement:: create ( ' MATCH (x) RETURN x LIMIT 100 ' )]);결과는 표준 형식의 행과 열로 반환됩니다.
// 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 ' );
}사이퍼 값 및 유형은 이러한 PHP 유형 및 클래스에 매핑됩니다.
| 사이퍼 | PHP |
|---|---|
| 널 | * null |
| 끈 | * string |
| 정수 | * int |
| 뜨다 | * float |
| 부울 | * bool |
| 지도 | * LaudisNeo4jTypesCypherMap |
| 목록 | * LaudisNeo4jTypesCypherList |
| 가리키다 | * LaudisNeo4jContractsPointInterface ** |
| 날짜 | * LaudisNeo4jTypesDate |
| 시간 | * LaudisNeo4jTypesTime |
| 로컬 타임 | * LaudisNeo4jTypesLocalTime |
| DateTime | * LaudisNeo4jTypesDateTime |
| DateTimezoneid | * LaudisNeo4jTypesDateTimeZoneId |
| 현지도 | * LaudisNeo4jTypesLocalDateTime |
| 지속 | * LaudisNeo4jTypesDuration |
| 마디 | LaudisNeo4jTypesNode |
| 관계 | LaudisNeo4jTypesRelationship |
| 길 | LaudisNeo4jTypesPath |
(*)이 항목은 볼트 프로토콜에서 매개 변수로 사용될 수 있으며 운전자가 자동으로 변환되므로 사이퍼에서 사용할 수 있습니다.
이 예제 외에도 DateTimeInterface Cypher의 DateTimeZoneId 에 매핑됩니다. 빈 또는 목록 유형 array 사이퍼 List 으로 변환되고 associative array map 으로 변환됩니다.
(**) 포인트 LaudisNeo4jTypesCartesianPoint PointInterface LaudisNeo4jTypesWGS843DPoint 구현 LaudisNeo4jTypesCartesian3DPoint LaudisNeo4jTypesWGS84Point 가지 유형 중 하나 일 수 있습니다.
사이퍼에는 목록과지도가 있습니다. 표준 PHP 배열이 두 가지를 모두 캡슐화함에 따라이 개념은 문제가 될 수 있습니다. 빈 배열을 매개 변수로 제공하면 빈 목록이나지도를 결정하는 것이 불가능합니다.
ParameterHelper 클래스는 이것에 이상적인 동반자입니다.
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| 드라이버 버전 | PHP 버전 | neo4j 버전 |
|---|---|---|
| ^2.8 | 7.4, ^8.0 | ^3.5, ^4.0 |
| ^3.0 | ^8.0 | ^4.0, ^5.0 |
| 특징 | 지원? |
|---|---|
| 입증 | 예 |
| 업무 | 예 |
| HTTP 프로토콜 | 예 |
| 볼트 프로토콜 | 예 |
| 무리 | 예 |
| 영기 | 예 |
| 졸트 프로토콜 | 예 |
| 북마크 | 예 |
(*) 볼트 프로토콜을 구현하기 위해 필요했습니다
(**) HTTP 프로토콜을 구현하는 데 필요했습니다
(***) 최적의 볼트 프로토콜 성능을 위해 설치할 수 있습니다
HTTP 드라이버를 사용할 계획이라면 PSR-7, PSR-17 및 PSR-18 구현이 프로젝트에 포함되어 있는지 확인하십시오. 아무것도 없으면 작곡가를 통해 설치할 수 있습니다.
composer require nyholm/psr7 nyholm/psr7-server kriswallsmith/buzz볼트 프로토콜과 HTTP 균일의 결과를 만들기 위해 드라이버는 결과 포맷터 (일명 수화기)를 제공합니다. 클라이언트는 이러한 포맷터로 구성 할 수 있습니다. 당신은 당신 자신의 것을 구현할 수도 있습니다.
기본 형식은 LaudisNeo4jFormattersOGMFormatter 이며 결과 형식 섹션에서 광범위하게 설명됩니다.
드라이버는 기본적으로 3 개의 포맷터를 제공하며, 이는 모두 Formatter 네임 스페이스에서 발견됩니다.
LaudisNeo4jFormatterBasicFormatter 는 모든 사이퍼 유형을 지우고 결과 맵의 모든 값을 스칼라, 널 또는 배열 값으로 간단히 반환합니다.LaudisNeo4jFormatterOGMFormatter 는 여기에 설명 된대로 사이퍼 유형을 PHP 유형에 매핑합니다.LaudisNeo4jFormatterSummarizedResultFormatter 는 모든 포맷터를 장식하고 광범위한 결과 요약을 추가합니다.클라이언트 빌더는 Formatter를 쉽게 변경하는 방법을 제공합니다.
$ client = Laudis Neo4j ClientBuilder:: create ()
-> withFormatter ( Laudis Neo4j Formatter SummarizedResultFormatter:: create ())
-> build ();
/**
* The client will now return a result, decorated with a summary.
*
* @var LaudisNeo4jDatabagsSummarizedResult $results
*/
$ summarisedResult = $ client -> run ( ' MATCH (x) RETURN x ' );
// The summary contains extensive information such as counters for changed values in the database,
// information on the database, potential notifications, timing, a (profiled) plan, the type of query
// and information on the server itself.
$ summary = $ summarisedResult -> getSummary ();
// The result is exactly the same as the default.
$ result = $ summarisedResult -> getResult (); 커스텀 포맷터를 사용하려면 LaudisNeo4jContractsFormatterInterface 구현하고 클라이언트 빌더를 사용할 때 제공하십시오.
여기에 설명 된 드라이버 API는 운전자의 주요 대상입니다. 이 때문에 클라이언트는 운전자 관리자에 지나지 않습니다. 운전자는 세션을 만듭니다. 세션은 거래를 통해 쿼리를 실행합니다.
이 동작으로 인해 다음과 같이 클라이언트에서 시작하는 각 개념에 액세스 할 수 있습니다.
use Laudis Neo4j ClientBuilder ;
// A builder is responsible for configuring the client on a high level.
$ builder = ClientBuilder:: create ();
// A client manages the drivers as configured by the builder.
$ client = $ builder -> build ();
// A driver manages connections and sessions.
$ driver = $ client -> getDriver ( ' default ' );
// A session manages transactions.
$ session = $ driver -> createSession ();
// A transaction is the atomic unit of the driver where are the cypher queries are chained.
$ transaction = $ session -> beginTransaction ();
// A transaction runs the actual queries
$ transaction -> run ( ' MATCH (x) RETURN count(x) ' );완전한 제어가 필요한 경우 사용자 정의 구성 객체로 각 객체를 제어 할 수 있습니다.
클라이언트는 사전 구성된 별칭을 기반으로 드라이버를 관리하고 쿼리를 올바른 드라이버로 라우팅합니다.
드라이버 객체는 NEO4J에 액세스 할 수있는 스레드 안전 백본입니다. 연결 풀을 소유하고 작업을 수행하기위한 세션을 생성 할 수 있습니다.
use Laudis Neo4j Basic Driver ;
use Laudis Neo4j Databags DriverConfiguration ;
$ driver = Driver:: create (
uri: ' neo4j://user:mypassword@Localhost:7687 ' ,
configuration: DriverConfiguration:: create ()-> withUserAgent ( ' MyApp/1.0.0 ' )
);세션은 인과 적으로 사슬의 트랜잭션 시퀀스를위한 경량 컨테이너입니다. 필요에 따라 연결 풀에서 연결을 빌리고 북마크를 사용하여 체인 트랜잭션을 빌립니다.
use Laudis Neo4j Databags SessionConfiguration ;
use Laudis Neo4j Enum AccessMode ;
$ session = $ driver -> createSession (SessionConfiguration:: create ()
-> withDatabase ( ' my-database ' )
-> withAccessMode (AccessMode:: READ ())
);트랜잭션은 하나 이상의 쿼리를 포함 할 수있는 원자가의 작업 단위입니다. 각 트랜잭션은 단일 연결 에 바인딩되며 인과 체인에 북마크 로 표시됩니다.
쿼리는 트랜잭션 내에서 실행 가능한 단위이며 사이퍼 문자열과 키 매개 변수 세트로 구성됩니다. 각 쿼리는 0 이상의 레코드를 포함 할 수있는 결과를 출력합니다.
결과 에는 헤더 메타 데이터, 컨텐츠 레코드 및 요약 메타 데이터로 구성된 쿼리 의 출력이 포함됩니다. NEO4J 4.0 이상에서 응용 프로그램은 결과 데이터의 흐름을 제어합니다.
URL 구성표는 드라이버를 구성하는 가장 쉬운 방법입니다.
구성 형식 :
'<scheme>://<user>:<password>@<host>:<port>?database=<database>'
기본 구성 :
bolt://localhost:7687?database=neo4j
이 라이브러리는 볼트, HTTP 및 NEO4J의 세 가지 드라이버를 지원합니다. URL의 체계 부분은 드라이버를 결정합니다.
| 운전사 | 계획 | 유효한 인증서 | 자체 서명 된 인증서 | 기능 |
|---|---|---|---|---|
| neo4j | neo4j | neo4j+s | neo4j+ssc | 볼트 위의 클라이언트 측 라우팅 |
| 볼트 | 볼트 | 볼트+s | 볼트+SSC | 볼트의 단일 서버 |
| http | http | https | PSR 클라이언트 구현을 통해 구성되었습니다 | HTTP의 단일 서버 |
운전자, 세션 및 트랜잭션은 구성 객체를 사용하여 구성 할 수 있습니다. 구성 옵션에 대한 개요는 다음과 같습니다.
| 이름 | 개념 | 설명 | 수업 |
|---|---|---|---|
| 사용자 에이전트 | 운전사 | 사용자 에이전트는 클라이언트를 NEO4J 서버로 식별하는 데 사용되었습니다. | DriverConfiguration |
| HTTP PSR 바인딩 | 운전사 | HTTP 프로토콜을 사용할 때 드라이버가 사용하는 관련 PSR 구현. | DriverConfiguration |
| 데이터 베이스 | 세션 | 연결할 데이터베이스. | SessionConfiguration |
| 페치 크기 | 세션 | 한 번에 가져 오는 행의 양. | SessionConfiguration |
| 액세스 모드 | 세션 | 서버에 액세스 할 때 기본 모드입니다. | SessionConfiguration |
| 북마크 | 세션 | 세션에 사용 된 북마크. (실험) | SessionConfiguration |
| 메타 데이터 | 거래 | 거래 중에 사용 된 메타 데이터. (실험) | TransactionConfiguration |
| 시간 초과 | 거래 | 타이밍 전 최대 시간. | TransactionConfiguration |
Code Example:
use Laudis Neo4j Databags DriverConfiguration ;
use Laudis Neo4j Databags SessionConfiguration ;
use Laudis Neo4j Databags TransactionConfiguration ;
$ client = Laudis Neo4j ClientBuilder:: create ()
-> withDefaultDriverConfiguration (DriverConfiguration:: default ()-> withUserAgent ( ' MyApp/1.0.0 ' ))
-> withDefaultSessionConfiguration (SessionConfiguration:: default ()-> withDatabase ( ' app-database ' ))
-> withDefaultTransactionConfiguration (TransactionConfiguration:: default ()-> withTimeout ( 5.0 ))
-> build ();
// The client will run the query on a driver with the provided config,
// which spawns a session with the provided session config
// and runs the query in a transaction with the provided transaction config
$ client -> run ( ' MATCH (x) RETURN count(x) AS count ' );
// More granular control can be achieved by requesting the concepts yourself:
$ tsx = $ client -> getDriver ( ' default ' )
-> createSession (SessionConfiguration:: default ()-> withDatabase ( ' management-database ' ))
-> beginTransaction ( null , TransactionConfiguration:: default ()-> withTimeout ( 200 ));
$ tsx -> run ( ' SOME REALLY LONG MANAGEMENT QUERY ' );
$ tsx -> commit ();