php7 环境 phalcon 如何使用mongodb数据库

phalcon 如何使用mongodb数据

官方文檔上面有这样的描述: Please note that if you are using the Mongo driver provided by PHP 7, the ODM will not work for you. There is an incubator adapter but all the Mongo code must be rewritten (new Bson type instead of arrays, no MongoId, no MongoDate, etc…). Please ensure that you test your code before upgrading to PHP 7 and/or Phalcon 3+ 大概意思就是若是你用的php7 提供的mongo驱动的话是不行的。 缘由是: phalcon提供的驱动是基于mongo的驱动, 可是php7 已经不支持了, php7使用的是mongodb的驱动。php

不过官方提供了解决方案,https://github.com/phalcon/incubator 按照文档上面的去用conposer安装。git

使用

use Phalcon\Mvc\Collection\Manager;
use Phalcon\Db\Adapter\MongoDB\Client;

// Initialise the mongo DB connection.
$di->setShared('mongo', function () {
    /** @var \Phalcon\DiInterface $this */
    $config = $this->getShared('config');
    
    if (!$config->database->mongo->username || !$config->database->mongo->password) {
        $dsn = 'mongodb://' . $config->database->mongo->host;
    } else {
        $dsn = sprintf(
            'mongodb://%s:%s@%s',
            $config->database->mongo->username,
            $config->database->mongo->password,
            $config->database->mongo->host
        );
    }
    
    $mongo = new Client($dsn);

    return $mongo->selectDatabase($config->database->mongo->dbname);
});

// Collection Manager is required for MongoDB
$di->setShared('collectionManager', function () {
    return new Manager();
});

这样配置好之后, 发现报错, 找不到 Client类,这个安装完成后是安装到了 composer 的目录 vender目录下面, 那么你须要在执行代码以前使用 composerautoload , 这样在找不到phalcon 扩展的状况下会自动加载 composer 的文件, 如此就没有问题了。github

使用

use Phalcon\Mvc\MongoCollection;

class UserCollection extends MongoCollection
{
    public $name;
    public $email;
    public $password;
    
    public function getSource()
    {
        return 'users';
    }
}

如此便可使用phalconcollection组件。mongodb

相关文章
相关标签/搜索