有没有人可以帮我介绍一个教程、库等,让我可以在CodeIgniter中使用MongoDB?
发布于 2011-11-19 01:33:51
我喜欢Stephen Curran的例子,因为它很简单,并且允许Mongo的接口,而不需要在Php中编写太多的功能,有时我倾向于发现一些巨大的抽象类,以满足我的需求。
我已经将他的示例扩展到包括数据库身份验证。转到这里:http://www.mongodb.org/display/DOCS/Security+and+Authentication要了解mongo身份验证,请不要忘记为您要连接的Mongo服务器启用身份验证。
我还将旧风格的构造函数改为__construct,并处理Mongo连接异常,因为它们可以显示您的用户名和密码。
config/mongo.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$config['mongo_server'] = 'localhost';
$config['mongo_dbname'] = 'my_mongo_db';
$config['mongo_username'] = 'mongo_user';
$config['mongo_password'] = 'password1234';
/* End of file mongo.php */
libraries/Mongo.php
<?php
class CI_Mongo extends Mongo{
protected $db;
function __construct()
{
// Fetch CodeIgniter instance
$ci = get_instance();
// Load Mongo configuration file
$ci->load->config('mongo');
// Fetch Mongo server and database configuration
$server = $ci->config->item('mongo_server');
$username = $ci->config->item('mongo_username');
$password = $ci->config->item('mongo_password');
$dbname = $ci->config->item('mongo_dbname');
// Initialise Mongo - Authentication required
try{
parent::__construct("mongodb://$username:$password@$server/$dbname");
$this->db = $this->$dbname;
}catch(MongoConnectionException $e){
//Don't show Mongo Exceptions as they can contain authentication info
$_error =& load_class('Exceptions', 'core');
exit($_error->show_error('MongoDB Connection Error', 'A MongoDB error occured while trying to connect to the database!', 'error_db'));
}catch(Exception $e){
$_error =& load_class('Exceptions', 'core');
exit($_error->show_error('MongoDB Error',$e->getMessage(), 'error_db'));
}
}
}
发布于 2010-02-12 19:55:34
在CodeIgniter中使用MongoDB与在其他任何地方使用没有太大不同。
您可以拼凑一个MongoDB库,该库将在构造函数中连接并存储$this->conn,以便稍后在方法中使用。
然后,要么直接使用控制器中的conn属性,要么在MongoDB库中创建一些方法来为您完成此操作。
看一看使用MongoDB的简单here教程。
我很乐意为你创建一个这样的库,但这是有代价的。:-p
发布于 2010-03-05 02:54:19
我正在使用带有CI的MongoDB,并提出了以下建议。它对我来说很有效,但我相信它可以进行一些调整。我稍后会考虑调整它,但现在它可以做我想要的事情。
我创建了一个名为"database_conn.php“的模型
class Database_Conn extends Model {
function _connect() {
$m = new Mongo();
$db = $m->selectDB( "YOUR DATABASE NAME" );
return $db;
}
}
然后,如果我需要连接到我的模型中的集合。
$collection = Database_Conn::_connect()->selectCollection( "COLLECTION NAME" );
https://stackoverflow.com/questions/2248789
复制相似问题