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

Mongo Php Adapter Laravel Package

alcaeus/mongo-php-adapter

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require alcaeus/mongo-php-adapter
    

    Ensure ext-mongodb (PHP driver) is installed (php -m | grep mongodb).

  2. Basic Usage:

    use MongoDB\Client as MongoClient;
    use Alcaeus\MongoClient\Connection;
    
    $client = new MongoClient('mongodb://localhost:27017');
    $adapter = new Connection($client);
    $collection = $adapter->selectCollection('db', 'collection');
    
  3. First Use Case: Replace legacy ext-mongo calls (e.g., mongo_connect()) with the adapter:

    // Old (deprecated)
    $conn = mongo_connect('localhost');
    // New
    $client = new MongoClient('mongodb://localhost');
    $adapter = new Connection($client);
    

Key Files

  • Connection.php: Core adapter class.
  • Cursor.php: Legacy cursor emulation.
  • Collection.php: Legacy collection wrapper.

Implementation Patterns

Workflow: Legacy Code Migration

  1. Wrap MongoDB\Client:

    $mongoClient = new MongoClient('mongodb://user:pass@host:port');
    $legacyAdapter = new Connection($mongoClient);
    
  2. Replace mongo_* Functions:

    • mongo_connect()new Connection($client)
    • mongo_select_db()$adapter->selectDB('db')
    • mongo_query()$collection->find($query)
  3. Cursor Handling:

    $cursor = $collection->find(['status' => 'active']);
    while ($cursor->advance()) {
        $doc = $cursor->current();
    }
    

Integration Tips

  • Laravel Eloquent: Use with jenssegers/mongodb for seamless ORM integration:
    $adapter = new Connection(new MongoClient(env('DB_CONNECTION')));
    config(['database.connections.mongodb.adapter' => $adapter]);
    
  • Query Builder: Chain legacy methods with modern queries:
    $result = $collection
        ->find()
        ->limit(10)
        ->sort(['createdAt' => -1]);
    
  • Transactions: Leverage MongoClient transactions via the adapter:
    $session = $client->startSession();
    $adapter->setSession($session);
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning: The package is deprecated (last release 2023). Prefer native ext-mongodb or mongodb/mongodb for new projects.

    • Workaround: Use only for legacy codebases.
  2. Method Mismatches:

    • mongo_insert() → Use $collection->insertOne().
    • mongo_find() → Use $collection->find() (returns Cursor).
    • Tip: Check legacy docs for 1:1 mappings.
  3. Type Inconsistencies:

    • Legacy mongo_id objects → Convert to MongoDB\BSON\ObjectId:
      $id = new MongoDB\BSON\ObjectId($legacyId->__toString());
      
  4. Session Handling:

    • Sessions must be manually passed to the adapter:
      $session = $client->startSession();
      $adapter->setSession($session); // Critical for transactions
      

Debugging

  • Enable Adapter Logging:
    $adapter = new Connection($client, [
        'logger' => new \Monolog\Logger('mongo_adapter'),
    ]);
    
  • Check for Deprecated Calls: Use xdebug to trace Alcaeus\MongoClient method calls in legacy code.

Extension Points

  1. Custom Adapters: Extend Connection to add domain-specific methods:
    class CustomAdapter extends Connection {
        public function findByEmail($email) {
            return $this->selectCollection('users')->find(['email' => $email]);
        }
    }
    
  2. Override Cursor Behavior: Extend Cursor to modify iteration logic (e.g., add caching):
    class CachedCursor extends Cursor {
        protected $cache = [];
        public function current() {
            if (!isset($this->cache[$this->key])) {
                $this->cache[$this->key] = parent::current();
            }
            return $this->cache[$this->key];
        }
    }
    
  3. Hybrid Queries: Combine legacy and modern syntax:
    $query = ['$query' => ['age' => ['$gt' => 18]], '$orderby' => ['name' => 1]];
    $result = $collection->find($query);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware