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

天涯浪子 提交于 2019-12-03 08:19:53

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的驱动。

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

使用

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 的文件, 如此就没有问题了。

使用

use Phalcon\Mvc\MongoCollection;

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

如此即可使用phalconcollection组件。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!