PHP code example of vinelab / neoclient

1. Go to this page and download the library: Download vinelab/neoclient library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

vinelab / neoclient example snippets




eoxygen\NeoClient\ClientBuilder;

$client = ClientBuilder::create()
    ->addConnection('default','http','localhost',7474)
    ->build();

$client = ClientBuilder::create()
    ->addDefaultLocalConnection()
    ->build();

$client = ClientBuilder::create()
    ->addDefaultLocalConnection()
    ->setDefaultTimeout(20) // <-- Timeout of 20 seconds for http requests
    ->build();

$root = $client->getRoot();

Array
    (
        [management] => http://localhost:7474/db/manage/
        [data] => http://localhost:7474/db/data/
    )

$version = $client->getNeo4jVersion();

// Returns (string) 2.2.1


$q = 'MATCH (n) RETURN count(n)';
$response = $client->sendCypherQuery($q);

Array
(
    [results] => Array
        (
            [0] => Array
                (
                    [columns] => Array
                        (
                            [0] => count(n)
                        )

                    [data] => Array
                        (
                            [0] => Array
                                (
                                    [row] => Array
                                        (
                                            [0] => 1
                                        )
......                                        

$client = ClientBuilder::create()
    ->addDefaultLocalConnection()
    ->setAutoFormatResponse(true)
    ->build();


$q = 'MATCH (n:Actor) RETURN n.name';
$client->sendCypherQuery($q);

$result = $client->getRows();

$labels = $client->getLabels();

[ "UriahHeep", "MyLabel", "Version", "Customer", "TestLabel" ]

$client->renameLabel('Person', 'User');

$client->createIndex('Person', 'email');

$client->listIndex('Person');

$personAndUserIndexes = $client->listIndexes(['Person','User']);

$allIndexes = $client->listIndexes();

$client->dropIndex('Person','email');

$client->isIndexed('User','username');

$client->createUniqueConstraint('User','username');

$client->createUniqueConstraint('User','username',true);

$client->dropUniqueConstraint('User','username');

$constraints = $client->getUniqueConstraints();

$query = 'MATCH (a:Actor)-[r]-(m:Movie) RETURN *';
$client->sendCypherQuery($query);

// Getting the graph Result
$result = $client->getResult();

// The raw response is still available :
$response = $client->getResponse();

// Getting all nodes

$nodes = $result->getNodes();

// Getting all movie nodes from the result
$movies = $result->getNodes('Movie');

// Getting all movie and Actor nodes from the result

$moviesAndActors = $result->getNodes(['Movie','Actor']);
// Returns you a collection of nodes objects

// If you want to group the nodes by labels, you can pass true as second argument to the getNodes method

$moviesAndActors = $result->getNodes(['Movie','Actor'], true);
// Returns an array with labels as keys ['Movie' => ['NodeObject1', 'NodeObject2']]


// Getting only one movie (returns in fact the first element of an array, but is handy when you expect only one node
$movie = $result->getSingleNode('Movie');

// Working with the relationships

$movie = $result->getSingleNode('Movie');
$actors = $movie->getRelationships('ACTS_IN');
// Or you may want to specify direction
$actors = $movie->getRelationships('ACTS_IN', 'IN');

// If you need only one relationship :
$actor = $movie->getSingleRelationship('ACTS_IN');

// Getting node/relationships properties

// Getting one property
$actor = $result->getSingleNode('Actor');
$name = $actor->getProperty('name');

// Getting all properties
$props = $actor->getProperties();

// Getting a set of properties
$props = $actor->getProperties(['name', 'date_of_birh']);

// Getting the node internal Id (Id of the Neo4j database)

$id = $actor->getId();

// Getting a node by id in the Result set

$node = $result->getNodeById(34);

// Counting Nodes And Relationships

$nbNodes = $result->getNodesCount();
$nbRels = $result->getRelationshipsCount();


// Since 2.2
// getConnectedNodes and getConnectedNode
// Shortcut bypassing the relationship and returning the connected nodes

$node->getConnectedNodes();
$node->getConnectedNodes('IN', 'KNOWS');
$node->getconnectedNodes('OUT', ['KNOWS','FOLLOWS']);
//Same arguments signature for getConnectedNode
$node->getConnectedNode(); // returns only one node


$q = 'MATCH (n:User)<-[:FOLLOWS]-(followers) RETURN n, collect(followers) as flwers';
$r = $client->sendCypherQuery($q)->getResult();

print_r($r->get('flwers')); // Returns an array of node objects

$tx = $client->prepareTransaction()
    ->pushQuery($q, $p)
    ->pushQuery($q2)
    ->pushQuery($q3)
    ->commit();

$transaction = $client->createTransaction();
$transaction->pushQuery('MERGE (n:User {id: 123}) RETURN n');
$transaction->pushQuery('MATCH (n) RETURN count(n)');
$transaction->commit();

// Other methods :
$transaction->rollback();
$transaction->getLastResult // Returns the result of the last transaction statements
$transaction->getResults() // Returns the results of all the statements

$client = ClientBuilder::create()
    ->addConnection('default', 'http', 'localhost', 7474)
    ->addConnection('testserver1', 'http', 'testserver.local', 7474)
    ->addConnection('testserver2', 'http', 'testserver2.local',7474)
    ->build();

$client->getRoot('default');
$client->sendCypherQuery('MATCH (n) RETURN count(n) as total', array(), 'testserver1');


$client = ClientBuilder::create()
    ->addConnection('server1', 'http', '193.147.213.3', 7474)
    ->addConnection('server2', 'http', '193.147.213.4', 7474)
    ->addConnection('server3', 'http', '193.147.213.7', 7474)
    ->setMasterConnection('server1') // Define the Master Connection by providing the connection alias
    ->setSlaveConnection('server2') // Idem for slave connections
    ->setSlaveConnection('server3')
    ->enableHAMode()
    ->build();


$client->sendWriteQuery('MERGE (n:User {firstname: "Chris"})'); // Will be sent to the "server1" connection

$client->sendReadQuery('MATCH (n:User) RETURN n'); // Will be sent to the "server2" connection


$client->getRoot($client->getWriteConnectionAlias()); // Will be run against the master connection

$client->listLabels($client->getReadConnectionAlias()); // Will be run agains the first found slave connection

$client->checkHAMaster('server1');      // Returns true|false
$client->checkHASlave('server2');       // Returns true|false
$client->checkHAAvailable('serverxxx'); // Returns master|slave|false

$client->sendCypherQuery($query, $params, $conn = null, $queryMode = Client::NEOCLIENT_QUERY_MODE_READ);

$client->createTransaction($conn = null, Client::NEOCLIENT_QUERY_MODE_WRITE);

$client->prepareTransaction($conn = null, Client::NEOCLIENT_QUERY_MODE_WRITE);

$client = ClientBuilder::create()
	// .. other settings
	->enableHAMode()
	->configureHAQueryModeHeaders($headerKey, $writeModeHeaderValue, $readModeHeaderValue)
	->build();

$client = ClientBuilder::create()
    ->addConnection('default', 'http', 'myserver.dev', 7474, true, 'username', 'password')
    ->build();

$client->changePassword('user', 'newPassword');

$client = ClientBuilder::create()
    ->addConnection('default', 'http', 'myserver.dev', 7474, true, 'username', 'password')
    ->build();

$client->listUsers();

$client->addUser('John', 'password');

$client->removeUser('user', 'password');

$client = ClientBuilder::create()
    ->addDefaultLocalConnection()
    ->addEventListener('foo.action', function (Event $event))
    ->build();

// Adding your own logging
$client = ClientBuilder::create()
    ->addDefaultLocalConnection()
    ->setLogger('app', MyLogger) // My Logger must implement Psr\Log\LoggerInterface
    ->build();


$client = ClientBuilder::create()
    ->addDefaultLocalConnection()
    ->createDefaultStreamLogger('name', '/path/to/your/log/file.log', 'debug')
    ->createDefaultChromePHPLogger('app', 'debug');
    ->build();



namespace Acme;

use Neoxygen\NeoClient\Command\AbstractCommand;

/**
* Class that is used to get the extensions listed in the API
*/
class MyCommand extends AbstractCommand
{
    public function execute()
    {
        $method = 'GET';
        $path = '/db/data/extensions';

        // The arguments for the send method of the http client are
        // $method, $path, $body = null, $connectionAlias = null

        return $this->httpClient->send($method, $path, null, $this->connection);
    }
}

$client = ClientBuilder::create()
    ->addDefaultLocalConnection()
    ->registerCommand('my_super_command', 'My\Command\Class\Namespace')
    ->build();

$command = $client->invoke('custom_get_extensions');
$extensions = $command->execute();
print_r($extensions);


use Neoxygen\NeoClient\Extension\NeoClientExtensionInterface;

class MyExtension implements NeoClientExtensionInterface
{
    public static function getAvailableCommands()
    {
        return array(
            'custom_get_extensions' => 'My\Command\Class',
            'custom_other_exec' => 'My\Other\Class'
            );
    }
}

$client = ClientBuilder::create()
    ->addDefaultLocalConnection()
    ->registerExtension('my_extension_alias', 'My\Extension\Class\Namespace')
    ->build();