How to use MongoDB without Composer

I know this might have been asked in a different forms but I’m in a situation where I need to use MongoDB PHP Library with out Composer. The official guide says that it is possible to use it without Composer but provides no example of how to load it into your project; it only mentions the following:

While not recommended, you may also manually install the library using
a source archive attached to the GitHub releases.

If you installed the library manually from a source archive, you will
need to manually configure autoloading:

  1. Map the top-level MongoDB\ namespace to the src/ directory using your preferred autoloader implementation.
  2. Manually require the src/functions.php file. This is necessary because PHP does not support autoloading for functions.

So, when I use the following example:

require('src/functions.php');

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

echo "Inserted with Object ID '{$result->getInsertedId()}'";

I get an error with the following message:

Uncaught Error: Class ‘MongoDB\Client’ not found in xxx

Please note that the driver and the PHP extension is installed and working fine, only that the library isn’t working.

Your help is highly appreciated!

1 Like

While the example code you shared did manually include the src/functions.php file, it omitted the first instruction from the documentation:

Map the top-level MongoDB\ namespace to the src/ directory using your preferred autoloader implementation.

“Autoloader implementation” here is referring to PSR-4. Composer provides the most common implementation, which is also highly optimized (see: Autoloader and Autoloader Optimization); however, any compliant implementation can be used. The PSR-4 example implementation is one other option.

If you do not use an autoloader, the only alternative is to manually require each class that you will use in your application (as discussed in this Stack Overflow answer). This is in addition to specifying use statements for classes (assuming you don’t intend to use fully qualified class names everywhere).

I’ve opened PHPLIB-937 to better clarify this in the library documentation.

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.