Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Neo4Jphp Laravel Package

everyman/neo4jphp

Neo4jPHP is a PHP wrapper for the Neo4j graph database REST API. Connect to a Neo4j server, inspect server info, and work with graph data and Cypher queries via a simple client. Installable via Composer.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require everyman/neo4jphp:dev-master
    

    Ensure vendor/autoload.php is included in your project.

  2. Basic Connection:

    $client = new Everyman\Neo4j\Client('localhost', 7474, 'username', 'password');
    $serverInfo = $client->getServerInfo();
    

    Verify connectivity by inspecting $serverInfo.

  3. First Use Case: Create a node and query it:

    $node = $client->createNode();
    $node->setProperty('name', 'Test Node');
    $node->save();
    
    $result = $client->query("MATCH (n) WHERE n.name = 'Test Node' RETURN n");
    $nodes = $result->getNodes();
    

Key Entry Points

  • Client: Central class for connection, queries, and batch operations.
  • Nodes/Relationships: Core entities with CRUD methods (save(), delete(), load()).
  • Queries: Cypher and Gremlin support via query() method.
  • Indexes: Create and manage indexes (createIndex(), dropIndex()).

Implementation Patterns

Common Workflows

1. CRUD Operations

Create/Update:

$node = $client->createNode();
$node->setProperty('title', 'Laravel Developer');
$node->setProperty('skills', ['PHP', 'GraphDB']);
$node->save(); // Auto-generates ID

Read:

$node = $client->loadNode($nodeId);
$skills = $node->getProperty('skills'); // Returns array

Delete:

$node->delete();

2. Relationships

$node1 = $client->loadNode($id1);
$node2 = $client->loadNode($id2);
$rel = $node1->createRelationship($node2, 'KNOWS');
$rel->setProperty('since', 2020);
$rel->save();

3. Batch Operations

$batch = $client->openBatch();
$batch->createNode()->setProperty('batch_item', true)->save();
$batch->close();

4. Cypher Queries

$result = $client->query(
    "MATCH (n:User)-[:FOLLOWS]->(m:User) RETURN n.name, m.name",
    ['params' => ['userId' => $userId]]
);
$rows = $result->getRows(); // Array of results

5. Indexes

$client->createIndex('users', 'name'); // Full-text index
$client->dropIndex('users', 'name');

Integration with Laravel

  • Service Provider: Bind the client to Laravel’s container in AppServiceProvider:

    public function register()
    {
        $this->app->singleton('neo4j', function () {
            return new Everyman\Neo4j\Client(config('neo4j.host'), config('neo4j.port'));
        });
    }
    
  • Eloquent-like Usage: Create a repository pattern for nodes:

    class UserRepository {
        protected $client;
    
        public function __construct(Everyman\Neo4j\Client $client) {
            $this->client = $client;
        }
    
        public function findByName($name) {
            $result = $this->client->query("MATCH (n:User {name: \$name}) RETURN n", ['name' => $name]);
            return $result->getNodes();
        }
    }
    
  • Query Builder: Extend the package to support Laravel’s query builder syntax (e.g., Node::where('name', 'John')->get()).


Gotchas and Tips

Pitfalls

  1. Authentication:

    • If using HTTPS/basic auth, ensure credentials are passed during client initialization:
      $client = new Everyman\Neo4j\Client('localhost', 7474, 'user', 'pass', true);
      
    • Gotcha: Forgetting auth may silently fail or return incomplete data.
  2. Cypher vs. Gremlin:

    • Cypher is recommended for most use cases (better readability, Laravel-friendly).
    • Gremlin is legacy; avoid unless maintaining old scripts.
  3. Transactions:

    • Neo4jPHP does not support transactions natively. Use batches for atomicity:
      $batch = $client->openBatch();
      try {
          $batch->createNode()->setProperty('data', 'critical')->save();
          $batch->close();
      } catch (\Exception $e) {
          $batch->rollback(); // Not natively supported; handle manually
      }
      
  4. Caching:

    • The package includes a EntityCache plugin. Enable it for performance:
      $client->setCache(new Everyman\Neo4j\Cache\EntityCache());
      
    • Gotcha: Cache invalidation must be manual (e.g., after delete()).
  5. Property Handling:

    • Setting a property to null deletes it:
      $node->setProperty('temp', null); // Removes 'temp' entirely
      
    • Use unsetProperty() explicitly for clarity.
  6. Error Handling:

    • Wrap operations in try-catch blocks:
      try {
          $client->query("MATCH (n) DELETE n"); // Dangerous!
      } catch (Everyman\Neo4j\Exception $e) {
          Log::error($e->getMessage());
      }
      
    • Common exceptions:
      • Everyman\Neo4j\Exception\ConnectionException: Network issues.
      • Everyman\Neo4j\Exception\QueryException: Invalid Cypher/Gremlin.
  7. Large Datasets:

    • Avoid loading all nodes at once. Use pagination in Cypher:
      $result = $client->query("MATCH (n) RETURN n SKIP 0 LIMIT 100");
      

Debugging Tips

  1. Enable Logging: Configure the client to log raw HTTP requests:

    $client->setLogger(new Everyman\Neo4j\Logger\FileLogger('/path/to/neo4j.log'));
    
  2. Check Server Info:

    $serverInfo = $client->getServerInfo();
    // Verify 'cypher' or 'gremlin' plugins are enabled.
    
  3. Validate Cypher: Test queries in Neo4j Browser first.

  4. Transport Issues:

    • If using HTTPS, ensure allow_self_signed is set:
      $client = new Everyman\Neo4j\Client('localhost', 7474, null, null, true, true);
      

Extension Points

  1. Custom Transport: Extend Everyman\Neo4j\Transport\TransportInterface for custom HTTP clients (e.g., Guzzle).

  2. Plugins: Add caching or logging plugins:

    $client->addPlugin(new Everyman\Neo4j\Plugin\MyCustomPlugin());
    
  3. Query Builder: Create a Laravel-like facade:

    class Neo4j {
        public static function query($cypher) {
            return app('neo4j')->query($cypher);
        }
    }
    
  4. Event Listeners: Listen for node/relationship changes (e.g., trigger Laravel events):

    $node->on('save', function () {
        event(new NodeSaved($node));
    });
    

Configuration Quirks

  • Port Defaults: Neo4j’s default HTTP port is 7474 (not 7687 for Bolt).
  • Index Types: Neo4jPHP supports exact, fulltext, and range indexes. Ensure your Neo4j version matches the expected syntax.
  • Case Sensitivity: Node labels and property names in Cypher are case-sensitive. Use consistent casing (e.g., snake_case for properties).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky