Using the PHP Library for MongoDB (PHPLIB)After the initial driver set-up, we will continue explaining how to get started with the MongoDB driver and corresponding userland library to write our first project. Installing the PHP Library with ComposerThe last thing we still need to install to get started on the application itself, is the PHP library. The library needs to be installed with » Composer, a package manager for PHP. Instructions for installing Composer on various platforms may be found on its website. Install the library by running: $ composer require mongodb/mongodb It will output something akin to: ./composer.json has been created Loading composer repositories with package information Updating dependencies (including require-dev) - Installing mongodb/mongodb (1.0.0) Downloading: 100% Writing lock file Generating autoload files
Composer will create several files: Using the PHP LibraryIn addition to managing your dependencies, Composer will also provide you with an autoloader (for those dependencies' classes). Ensure that it is included at the start of your script or in your application's bootstrap code:
<?php With this done, you can now use any of the functionality as described in the » library documentation.
If you have previously used the old driver (i.e. As an example, this is how you insert a document into the beers collection of the demo database:
<?php
Instead of injecting the generated
After insertion, you can of course also query the data that you have just
inserted. For that, you use the
<?php While it may not be apparent in the examples, BSON documents and arrays are unserialized as type classes in the library by default. These classes ensure that values preserve their type when being serialized back into BSON, which avoids a caveat in the old driver where arrays might turn into documents, and vice versa. Additionally, the classes extend ArrayObject for enhanced usability. You can find more information on how serialization and deserialization between PHP variables and BSON is handled by the driver and library by reading the Persisting Data specification. |