phpmongodbdoctrine-ormslimphp-mongodb

Connecting slim php to mongodb doctrine


I am using this slim php skeleton for an mvc structure. It has doctrine connection as well https://github.com/semhoun/slim-skeleton-mvc

I want to connect to my mongodb server and this is the doctrine mongodb package https://www.doctrine-project.org/projects/mongodb-odm.html

I have it installed and setup my bootstrap.php like the docs say on the setup step https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/2.2/reference/introduction.html#setup

The settings file in my slim framework looks like this

<?php
declare(strict_types=1);

use DI\ContainerBuilder;
use Monolog\Logger;

return function (ContainerBuilder $containerBuilder) {
    $rootPath = realpath(__DIR__ . '/..');

    // Global Settings Object
    $containerBuilder->addDefinitions([
        'settings' => [
            // Base path
            'base_path' => '',
        
            // Is debug mode
            'debug' => (getenv('APPLICATION_ENV') != 'production'),

            // 'Temprorary directory
            'temporary_path' => $rootPath . '/var/tmp',

            // Route cache
            'route_cache' =>$rootPath . '/var/cache/routes',

            // View settings
            'view' => [
                'template_path' =>$rootPath . '/tmpl',
                'twig' => [
                    'cache' =>$rootPath . '/var/cache/twig',
                    'debug' => (getenv('APPLICATION_ENV') != 'production'),
                    'auto_reload' => true,
                ],
            ],

            // doctrine settings
            'doctrine' => [
                'meta' => [
                    'entity_path' => [ $rootPath . '/src/Entity' ],
                    'auto_generate_proxies' => true,
                    'proxy_dir' => $rootPath . '/var/cache/proxies',
                    'cache' => null,
                ],
                'connection' => [
                    'driver' => 'pdo_sqlite',
                    'path' => $rootPath . '/var/blog.sqlite'
                ]
            ],

            // monolog settings
            'logger' => [
                'name' => 'app',
                'path' =>  getenv('docker') ? 'php://stdout' : $rootPath . '/var/log/app.log',
                'level' => (getenv('APPLICATION_ENV') != 'production') ? Logger::DEBUG : Logger::INFO,
            ]
        ],
    ]);

    if (getenv('APPLICATION_ENV') == 'production') { // Should be set to true in production
        $containerBuilder->enableCompilation($rootPath . '/var/cache');
    }
};

How can i connect to my mongodb server and use it in my controllers?


Solution

  • Make sure that ext-mongodb in stalled.

    extension=mongodb
    

    Install the Doctrine MongoDB ODM library:

    composer require doctrine/mongodb-odm
    

    Add a DI container definition for DocumentManager::class:

    <?php
    
    use Doctrine\ODM\MongoDB\Configuration;
    use Doctrine\ODM\MongoDB\DocumentManager;
    use MongoDB\Client;
    use Psr\Container\ContainerInterface;
    
    return [
        // ...
    
        DocumentManager::class => function (ContainerInterface $container) {
            $settings = $container->get('settings')['mongodb'];
    
            // URI: mongodb://127.0.0.1
            $client = new Client($settings['uri']);
            $config = new Configuration();
            // ...
    
            return DocumentManager::create($client, $config);
        },
    ];
    
    

    Then use dependency injection and declare DocumentManager in your Repository class constructor.

    Usage example:

    $address = new Address();
    $address->setAddress('555 Doctrine Rd.');
    $address->setCity('Nashville');
    $address->setState('TN');
    $address->setZipcode('37209');
    
    $this->dm->persist($address);