CI 묻고 답하기

제목 컨트롤러 생성자에 파라미터를 사용하는 방식
글쓴이 기스버 작성시각 2015/05/31 20:26:03
댓글 : 2 추천 : 0 스크랩 : 0 조회수 : 15636   RSS
 제가 게시판(?) 기능을 구현 하였는데, 서로 다른 주제의 두가지 게시판을 만들고 싶습니다. 전체적으로 달라지는 부분은 데이터 베이스 이름 뿐인거 같아서(같은 스키마를 가지고 있습니다.), 때문에 재활용 가능하게 바꾸고 싶습니다.

 여러가지 방식이 있을텐데, 제가 생각해본 방식은 우선 공통적인 Board.php 컨트롤러를 만들고 생성자에 데이터베이스 이름을 초기화 해주는 방식을 추가합니다.

 후에 주제1(A.php), 주제2(B.php)를 만들고 둘다 Board.php를 상속하고 생성자에서 데이터 베이스 이름만을 달리하는 방식으로 사용하고 싶습니다.
 
 이런 방식으로 하기 위해서는 Controller생성자에 인자를 전달해야하는데 라이브러리를 불러오는 것 처럼 단순히 인자를 전달하는 방식이 존재 하지 않는 것 같아서요.

 또한 Controller끼리 서로 상속할 수 있는 방식이 있을까요? 없는거 같아서 코어를 확장해서 MY_Controller를 생성해서 그것을 상속해오고 싶은데 코어를 확장한 파일은 데이터 베이스를 불러올 때 에러가 나는 것 같아서요ㅠㅠ(다른것이 에러가 나는 것 일 수도 있습니다.)

질문을 요약하자면

 1. 컨트롤러도 마찬가지로 라이브러리를 불러올때 처럼 인자를 전달해 줄 수 없나요?

 2. 애초에 이런 발상이 잘못 된 것이고 다른식으로 구현해야 더 편하고 더 재활용하기 쉽게 만들 수 있나요? 그렇다면 그 방식은 어떤 방식일까요 ㅠㅠ

 3. Controller끼리, 혹은 Model끼리 이런식으로 서로 상속 할 수 있나요 ?? (테스트 해봤을때 존재하지 않다고 나와서요ㅠㅠ 제 테스트 방식이 잘못 된 것 같기도 해서 질문 남깁니다!!ㅜㅜ)

제가 너무 초보여서, 질문자체도 두서가 없네요. 항상 커뮤니티에서 많은 도움 얻고 있습니다.
아래는 데이터베이스명만 다른 두개의 파일입니다!!
항상 감사합니다



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

class Topic extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('topic_model');

    }

    function index()
    {
        $this->_header();
        $this->_sidebar();
        $this->_footer();
    }

    function get($id)
    {
        $this->_header();
        $this->_sidebar();
        $topic = $this->topic_model->get($id);
        $this->load->view('get',array('topic'=>$topic));
        $this->_footer();
    }

    function add()
    {
        //로그인이 필요.

        //로그인이 되어있지 않다면 로그인 페이지로 리다이렉션.
        if($this->session->userdata('is_login') == FALSE)
        {
            redirect('/auth/login?returnURL='.rawurlencode(site_url('/topic/add')));
        }

        $this->_header();
        $this->_sidebar();
        $this->load->library('form_validation');
        $this->form_validation->set_rules('title', '제목', 'required');
        $this->form_validation->set_rules('description', '설명', 'required');
        if($this->form_validation->run() == FALSE)
        {
            $this->load->view('add');
            $this->_footer();
        }
        else
        {
            $addData = array(
                'title' => $this->input->post('title'), 
                'description' => $this->input->post('description'),
                );
            $topic_id = $this->topic_model->add($addData);
            redirect('/topic/get/'.$topic_id);
        }

    }

    function delete()
    {    
        $id = $this->input->get('id');
        if($this->session->userdata('is_login') == FALSE)
        {
            redirect('/auth/login?returnURL='.rawurlencode(site_url('/topic/get/'.$id)));
        }
        $this->load->model('topic_model');
        $this->topic_model->delete($id);
        redirect('/topic/get/'.($id-1));
    }

    function upload()
    {
        $config['upload_path'] = '/static/user';
        $this->load->library('upload', $config);
        if ($this->upload->do_upload('upload') == FALSE) 
        {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('add');
            $this->_footer();
        }
        else
        {
            $CKEditorFuncNum = $this->input->get('CKEditorFuncNum');
                   $data = $this->upload->data();            
              $filename = $data['file_name'];
                $url = '/static/user/'.$filename;
                echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction('".$CKEditorFuncNum."', '".$url."', '전송에 성공 했습니다')</script>";    
        }

    }
}
 ?>

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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

class Thought extends MY_Controller
{
    
    function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->model('thought_model');

    }

    function index()
    {
        $this->_header();
        $this->_sidebar2();
        $this->_footer();
    }

    function get($id)
    {
        $this->_header();
        $this->_sidebar2();
        $topic = $this->thought_model->get($id);
        $this->load->view('get',array('topic'=>$topic));
        $this->_footer();
    }

    function add()
    {
        //로그인이 필요.

        //로그인이 되어있지 않다면 로그인 페이지로 리다이렉션.
        if($this->session->userdata('is_login') == FALSE)
        {
            redirect('/auth/login?returnURL='.rawurlencode(site_url('/thought/add')));
        }

        $this->_header();
        $this->_sidebar2();
        $this->load->library('form_validation');
        $this->form_validation->set_rules('title', '제목', 'required');
        $this->form_validation->set_rules('description', '설명', 'required');
        if($this->form_validation->run() == FALSE)
        {
            $this->load->view('add');
            $this->_footer();
        }
        else
        {
            $addData = array(
                'title' => $this->input->post('title'), 
                'description' => $this->input->post('description'),
                );
            $topic_id = $this->thought_model->add($addData);
            redirect('/thought/get/'.$topic_id);
        }

    }

    function delete()
    {    
        $id = $this->input->get('id');
        if($this->session->userdata('is_login') == FALSE)
        {
            redirect('/auth/login?returnURL='.rawurlencode(site_url('/thought/get/'.$id)));
        }
        $this->load->model('thought_model');
        $this->thought_model->delete($id);
        redirect('/thought/get/'.($id-1));
    }

    function upload()
    {
        $config['upload_path'] = '/static/user';
        $this->load->library('upload', $config);
        if ($this->upload->do_upload('upload') == FALSE) 
        {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('add');
            $this->_footer();
        }
        else
        {
            $CKEditorFuncNum = $this->input->get('CKEditorFuncNum');
                   $data = $this->upload->data();            
              $filename = $data['file_name'];
                $url = '/static/user/'.$filename;
                echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction('".$CKEditorFuncNum."', '".$url."', '전송에 성공 했습니다')</script>";    
        }

    }



}

?>
 
태그 생성자,컨트롤러,인자
 다음글 CI에서 사용하는 세션을 네이티브PHP 에서 복호화하는... (1)
 이전글 PHP5.5 + CodeIgniter 2.2 환경에서 ... (5)

댓글

변종원(웅파) / 2015/06/01 10:39:26 / 추천 0
ci가 아니라 php클래스에서 a와 b 컨트롤러에서 상속받은 board의 생성자에 꺼꾸로 데이터를 주는 방법이 있던가요? ^^;

주소를 이용해서 이건 공지사항이다 이건 자유게시판이다라고 명시를 하고 그걸 프로그램(컨트롤러던지 클래스던지)에서
사용해야 합니다. 

포럼소스 받아서 포럼의 동작구조를 한번 보세요. 포럼의 주소방식이 싫으면 a.com/board/list/qna/ 형태로 쓰면 됩니다.
(쿼리스트링 방식이라면 board.php?l=list&t=qna 정도가 되겠죠)

왜 a와 b로 나누는지에 대한 부분이 없어서 일반적인 상황으로 이야기 하자면 뷰 확장성과 관리 측면에서도 맞지 않습니다.
여러개의 뷰(여러 형태)가 존재해야 한다면 board 컨트롤러 1개와 여러 개의 뷰로 처리할 수 있습니다.
다른 사람이 만든 게시판을 분석하는 것 아주 중요합니다. 여러 개의 게시판이 비슷한 구조와 형태를 가지고 있다면
그건 뭔가 이유가 있어서겠죠. ^^
기스버 / 2015/06/01 15:40:27 / 추천 0
 부족한 제 질문에 직접 답변 달아주셔서 감사합니다!!!!
php클래스에서 그런 방식이 존재치 않았군요. php를 좀 더 공부했어야 했는데ㅠㅠ
한번 소스를 보기전에 제 스스로 생각해보고 싶었습니다. 나중에 볼 때 왜 저런 방식으로 구현하는것일까를 좀더 이해하고 싶었습니다. 
포럼 소스를 다운받아서 공부해보도록 하겠습니다. 좋은 답변 감사합니다 웅파님 궁금증이 해결되었습니다.!!!