php – Phalcon MongoDB


php7.0 , Phalcon 3.2 , MongoDB 3.2.14

I want to connect to the database, but the Phalcon documentation describes how to set up a connection through MongoClient () and work only through it, although it is outdated for a long time and generally deprecated in the seven. How can I make Phalcon friends with the modern and cozy \MongoDB\Driver\Manager() ? Because in services.php I just set it up at the very least, it doesn't seem to swear, the code is as follows:

* MongoDB connection
$di->set( "mongo", function () {
       $config = $this->getConfig();

        $db_string = sprintf( 'mongodb://%s:%s/%s', $config->mongodb->host, $config->mongodb->port, $config->mongodb->database );

        if( isset( $config->mongodb->user ) AND isset( $config->mongodb->password ) ) {
            $db_string = sprintf( 'mongodb://%s:%s@%s:%s/%s',
                $config->mongodb->database );

        try {
            return new \MongoDB\Driver\Manager( $db_string );
        } catch (MongoConnectionException $e) {
            die( 'Failed to connect to MongoDB '.$e->getMessage() );

But he doesn't like the models. I write in app/models/User.php :

use Phalcon\Mvc\Collection;

class User extends Collection
    public function initialize()

I call in the controller:

class IndexController extends ControllerBase
    public function indexAction()
        echo User::count();

He writes this:

Call to undefined method ::selectcollection()
#0 [internal function]: Phalcon\Mvc\Collection::_getGroupResultset(Array, Object(User), Object(MongoDB\Driver\Manager))
#1 /var/www/testing/app/controllers/IndexController.php(8): Phalcon\Mvc\Collection::count()
#2 [internal function]: IndexController->indexAction()
#3 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(IndexController), 'indexAction', Array)
#4 [internal function]: Phalcon\Dispatcher->_dispatch()
#5 [internal function]: Phalcon\Dispatcher->dispatch()
#6 /var/www/testing/public/index.php(42): Phalcon\Mvc\Application->handle()
#7 {main}

Как победить?


First I installed Phalcon incubator using composer into my vendor directory:

composer require phalcon/incubator

Then I make sure that vendor libraries are loaded:

include_once SITE_ROOT . 'vendor/autoload.php';

Then I use \Phalcon\Db\Adapter\MongoDB\Client() found in vendor/phalcon/incubator/Library/Phalcon/Db/Adapter/MongoDB/Client.php

In services.php:

$di->setShared('mongo', function () use ($config) {
    $mongo = new \Phalcon\Db\Adapter\MongoDB\Client();
    return $mongo->selectDatabase($config->mongodb->dbname);

Then ensure my MongoCollection extends \Phalcon\Mvc\MongoCollection (vendor/phalcon/incubator/Library/Phalcon/Mvc/MongoCollection.php).



namespace Common\Models;

class MyCollectionStats extends \Phalcon\Mvc\MongoCollection

The answer was found here . I hope this will help someone in the future 🙂

Scroll to Top