Codeigniter

[Codeigniter] CI3 MongoDB 연동 on windows

hiolivia 2022. 4. 15. 14:06

프로젝트 중 CI와 MongoDB를 사용해야 할 일이 생겼는데 구글링 해 본 결과, 자료가 생각보다 많지 않았습니다.

특히 구글에 올라와 있는 대부분의 코드를 적용시켜도 구현이 안되었는데 마지막으로 시도한 코드가 working 했습니다!

저는 php 7.2, CI3 버전을 사용하고 있고, 윈도우 기반입니다.

 

파일 위치

application/config/mongodb.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

$config['host'] = 'DB IP주소';
$config['port'] = 포트번호;
$config['username'] = '유저이름';
$config['password'] = '비밀번호';
$config['database'] = '테이블명';

?>

 

application/libraries/mongodb.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MongoDB {
	
	private $conn;
	
	function __construct() {
		$this->ci =& get_instance();
		$this->ci->load->config('mongodb');
		
		$host = $this->ci->config->item('host');
		$port = $this->ci->config->item('port');
		$username = $this->ci->config->item('username');
		$password = $this->ci->config->item('password');
		$database = $this->ci->config->item('database');
		
		try {
			$this->ci->conn = new MongoDB\Driver\Manager('mongodb://' . $username . ':' . $password . '@' . $host. ':' . $port . '/' .$database);
		} catch(MongoDB\Driver\Exception\MongoConnectionException $ex) {
			show_error('Couldn\'t connect to mongodb: ' . $ex->getMessage(), 500);
		}
	}
	
	function getConn() {
		return $this->ci->conn;
	}
	
}

 

이렇게 두 개의 파일을 생성해주신 다음 model로 이동해보겠습니다!

 

application/models/Mongo_model.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mongo_model extends CI_Model{

	private $conn;

    function __construct()
    {   
        parent::__construct();
        $this->load->library('mongodb');
	$this->conn = $this->mongodb->getConn(); //DB연결
    }
    
    function getData()
    {
    	//데이터 받아오는 쿼리 executeQeury 후 return
    }

}
?>

 

application/views/mongo_controller.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mongo_controller extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('Mongo_model');
	}

	public function index()
	{
		$data = $this->Mongo_model->getData();
        	print_r($data); //데이터를 가져왔는지 테스트
	}
}

 

따라서 파일을 추가하면 MongoDB와 연동도 잘되고 데이터도 잘 가져와집니다!