我試圖用phalcon API框架連接mongoDB。 我的代碼是象下面這樣:MongoDB和Phalcon API
index.php文件
<?php
if ($handle = opendir('include/models')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.php$/', $entry)) {
require_once "include/models/$entry";
}
}
closedir($handle);
}
require 'vendor/autoload.php';
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\Model;
$app = new Phalcon\Mvc\Micro();
$di = new \Phalcon\DI\FactoryDefault();
$config = new Phalcon\Config\Adapter\Ini('include/config/config.ini');
// Simple database connection to localhost
$di->set('mongo', function() {
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
return $manager->selectDb("MyApi");
},true);
$di->set('collectionManager', function() {
return new Phalcon\Mvc\Collection\Manager();
});
$app->setDI($di);
$directory = new User_detail();
$app->get('/userdetail/{code}', function ($code) use ($app,$directory) {
$directory->getUser($app,$code);
});
$app->notFound(function() use ($app) {
$app->response->setStatusCode(424, "Method Failed")->sendHeaders();
echo json_encode(array('status' => 'ERROR', 'messages' => "Method Failed"));
});
$app->handle();
?>
型號文件User_detail.php
<?php
use Phalcon\Mvc\Collection;
use Phalcon\Mvc\Model;
use MongoDB\Driver\Manager;
use Phalcon\Mvc\Micro;
use Phalcon\Db\Column;
class User_detail extends Collection
{
public function initialize()
{
$this->setSource("User");
}
function getUser($app,$code)
{
$robot = User_detail::findFirst(
[
[
"Name" => "android",
]
]
);
echo $robot->Name; die;
}
}
?>
我得到錯誤的
Error: Call to undefined method MongoDB\Driver\Manager::selectDb() in index.php
什麼是錯的它?
你的錯誤告訴你的方法'selectDb'不在類'MongoDB的\驅動程序\ Manager'存在。如果您打開該課程,您會看到該方法在那裏不存在...因此會給您提供錯誤。 – Timothy
謝謝!你有什麼想法嗎,哪個函數用於選擇數據庫? – Khushal
如果我沒有弄錯,請使用:'$ manager = new MongoClient();返回$ manager-> selectDB(「MyApi」);'。檢查文檔:https://docs.phalconphp.com/en/3.0.1/reference/odm.html#setting-a-connection。但是如果你使用的是PHP7,你應該使用phalcon孵化器:https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Db/Adapter – Timothy