用一个函数解决ThinkPHP 连接 MySQL与 MongoDB,请注意M函数
1. config.php设置
//.配置MySQL数据库
'DB_MYSQL' => array(
'db_type'=>'mysqli',
'db_user'=>'用户名',
'db_pwd'=>'密码',
'db_host'=>'127.0.0.1',
'db_port'=>'3306',
'db_name'=>'数据库名',
'db_charset'=>'utf8',
),
//.配置MongoDB数据库
'DB_MONGO' => array(
'db_type'=>'mongo',
'db_user'=>'用户名',
'db_pwd'=>'密码',
'db_host'=>'localhost',
'db_port'=>'27017',
'db_name'=>'数据库名',
),
2. 写一个M函数,实现数据库的调用
//. 调用MONGO和MYSQL数据库
protected function M( $table_name = '', $db_type = 'DB_MYSQL' ){
$db_config = C($db_type);
$db_prefix = C('DB_PREFIX');
if( $table_name == '' ){ return false; }
if( $db_type == 'DB_MYSQL' ){
return M( $table_name , $db_prefix , $db_config );
}else if( $db_type == 'DB_MONGO' ){
return M( '\Think\Model\MongoModel:' . $table_name , $db_prefix , $db_config );
}else{
return false;
}
}//;
3. 调用M函数的实例
//. 调用自定义的M函数
//. 连接MySQL数据库
echo 'Mysql:';
$list = $this->M('user','DB_MYSQL')->select();
dump( $list );
//. 连接MongoDB数据库
echo 'Mongo:';
$list = $this->M('user','DB_MONGO')->select();
dump( $list );
希望对您有所帮助!!!