ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [CodeIgniter] 3. Todo 애플리케이션 프로젝트
    Web/CodeIgniter 2015. 8. 21. 16:43

    이번 장에서는 할 일을 관리하는 애플리케이션을 만들어보면서 CodeIgniter의 개념을 익혀보도록 하겠습니다.


    CodeIgniter는 MVC 패턴으로 되어있습니다. 지금 당장 MVC 패턴이 무엇인지 알 필요는 없습니다.


    3장을 마치면 MVC에 대해 감을 잡을 수 있습니다.


    다만, 여기서는 MVC 패턴으로 되어 있기 때문에 CodeIgniter로 애플리케이션을 개발할 때는 모델, 뷰, 컨트롤러를 각각 만들어야 한다는 점만 알면 됩니다.


    먼저, 웹 서버 루트에 todo 디렉터리를 만들고 여기에 CodeIgniter를 복사합니다.


     - xampp/htdocs/todo


    todo 디렉터리에 CodeIgniter가 제데로 설치되었다면 주소창에 localhost/todo 를 입력했을 때 CodeIgniter 초기 화면이 표시됩니다.



     








    3.1 데이터베이스 설정하기

     2.1에서 구성한 윈도우 환경에서 MySQL에 todo 데이터베이스를 생성하고, todo 데이터베이스에 items 테이블을 생성합니다.






     items 테이블


     int         id

     varchar    content

     date        created_on

     date        due_date

     int        use





     윈도우 명령창(CMD)을 열고 다음 명령어를 실행하여 MySQL에 items 테이블을 생성해보겠습니다.


      



     

     cd \

     cd xampp

     cd mysql

     cd bin

     mysqladmin -uroot -p create todo

     mysql -uroot -p todo


     create table items (

     id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,

     content VARCHAR(200) NULL,

     created_on DATE NULL,

     due_date DATE NULL,

     used INT(1) NOT NULL DEFAULT 1

     );


     INSERT INTO items(content, created_on, due_date) VALUES('미팅', '2015-08-11', '2015-08-12');

     INSERT INTO items(content, created_on, due_date) VALUES('스터디', '2015-08-13', '2015-08-15');







     자 이렇게 해서 DB 생성 및 테이블 생성, 샘플 데이터 추가까지 마무리 했습니다.


     모델을 이용하려면 데이터베이스에 연결해야 하는데 그 부분은 application/config/database.php사용자, 비밀번호, HOST, 데이터베이스 명을 입력합니다.



    * database.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    /*
    | -------------------------------------------------------------------
    | DATABASE CONNECTIVITY SETTINGS
    | -------------------------------------------------------------------
    | This file will contain the settings needed to access your database.
    |
    | For complete instructions please consult the 'Database Connection'
    | page of the User Guide.
    |
    | -------------------------------------------------------------------
    | EXPLANATION OF VARIABLES
    | -------------------------------------------------------------------
    |
    |    ['hostname'] The hostname of your database server.
    |    ['username'] The username used to connect to the database
    |    ['password'] The password used to connect to the database
    |    ['database'] The name of the database you want to connect to
    |    ['dbdriver'] The database type. ie: mysql.  Currently supported:
                     mysql, mysqli, postgre, odbc, mssql, sqlite, oci8
    |    ['dbprefix'] You can add an optional prefix, which will be added
    |                 to the table name when using the  Active Record class
    |    ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
    |    ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
    |    ['cache_on'] TRUE/FALSE - Enables/disables query caching
    |    ['cachedir'] The path to the folder where cache files should be stored
    |    ['char_set'] The character set used in communicating with the database
    |    ['dbcollat'] The character collation used in communicating with the database
    |                 NOTE: For MySQL and MySQLi databases, this setting is only used
    |                  as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
    |                 (and in table creation queries made with DB Forge).
    |                  There is an incompatibility in PHP with mysql_real_escape_string() which
    |                  can make your site vulnerable to SQL injection if you are using a
    |                  multi-byte character set and are running versions lower than these.
    |                  Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
    |    ['swap_pre'] A default table prefix that should be swapped with the dbprefix
    |    ['autoinit'] Whether or not to automatically initialize the database.
    |    ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
    |                            - good for ensuring strict SQL while developing
    |
    | The $active_group variable lets you choose which connection group to
    | make active.  By default there is only one group (the 'default' group).
    |
    | The $active_record variables lets you determine whether or not to load
    | the active record class
    */
     
    $active_group = 'default';
    $active_record = TRUE;
     
    $db['default']['hostname'= 'localhost';
    $db['default']['username'= 'root';
    $db['default']['password'= '*******'// 자신의 root 비밀번호 입력해주세요.
    $db['default']['database'= 'todo';
    $db['default']['dbdriver'= 'mysql';
    $db['default']['dbprefix'= '';
    $db['default']['pconnect'= FALSE;
    $db['default']['db_debug'= TRUE;
    $db['default']['cache_on'= FALSE;
    $db['default']['cachedir'= '';
    $db['default']['char_set'= 'utf8';
    $db['default']['dbcollat'= 'utf8_general_ci';
    $db['default']['swap_pre'= '';
    $db['default']['autoinit'= TRUE;
    $db['default']['stricton'= FALSE;
     
     
    /* End of file database.php */
    /* Location: ./application/config/database.php */
    cs








    3.2 목록 만들기

     todo 컨트롤러에서는 조회, 목록, 쓰기, 삭제 등의 액션을 제어합니다. 목록 함수의 경우 목록 컨트롤러(C)는 모델(M)에서 데이터베이스의 해당 내용을 가져와서 뷰(V)에 전달하여 화면을 출력하도록 합니다.


     3.1절에서 입력한 샘플 데이터의 목록을 화면에 출력하는 목록 함수를 만들어 보겠습니다. 



     * todo/application/controllers/main.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
    /*
     * todo 컨트롤러
     */
     
    class Main extends CI_Controller 
    {
        function __construct() 
        {
            parent::__construct();
            $this->load->database();
            $this->load->model('todo_m');
            $this->load->helper(array('url''date'));
        }
        
        public function index() 
        {
            $this->lists();
        }
        
        /*
         * todo 목록
         */
        public function lists() 
        {
            $data['list'= $this->todo_m->get_list();
            
            $this->load->view('todo/list_v'$data);
        }
    }
     
    /* End of file main.php */
    /* Location: ./application/controllers/main.php */
    cs




     Line 1: 보안과 관련이 있어서 그대로 쓰는 것이 좋습니다. 

     Line 6: 클래스 명은 컨트롤러 파일명(main.php)과 동일합니다. 눈여겨 봐야할 것은 클래스 명 첫 글자가 대문자라는 점입니다. 파일명은 소문자, 클래스 명은 첫글자만 대문자라는 것을 알아두세요.

     Line 24: todo 목록의 실제 함수인 lists를 만듭니다. http://localhost/todo/index.php/main/lists의 주소로 호출됩니다.

     Line 26: todo_m 모델에서 get_list() 함수를 호출하여 todo 목록 내용을 가져와서 뷰에 저달하는 $data['list'] 변수에 담습니다. 뷰에 여러 개의 데이터를 전달 할 수 있으므로 2차 배열 형태로 만듭니다.




     데이터베이스에서 목록 내용을 불러오고 화면에 출력하는 부분은 Line 26, 28번이고 나머지 부분은 통상적으로 프로그래밍할 때 사용되는 부분입니다.


     클래스 선언 부분과 생성자에서 데이터베이스 연결, 라이브러리나 모델, 헬퍼 로딩하는 부분을 자세히 살펴보시기 바랍니다.



     이제 모델 소스를 살펴보도록 하겠습니다. 모델은 전적으로 데이터 부분을 담당합니다. todo/application/models/todo_m.php 파일을 만들고 다음 내용을 입력합니다.





    * todo_m.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
     
    /*
     * todo 모델
     *
     */
     
    class Todo_m extends CI_Model 
    {
        function __construct() 
        {
            parent::__construct();
        }
        
        function get_list() {
            $sql = "SELECT * FROM items";
            
            $query = $this->db->query($sql);
            
            $result = $query->result();
            
            return $result;
        }
    }
     
    /* End of file todo_m.php */
    /* Location: ./application/Models/todo_m.php  */
    cs




     Line 8: 컨트롤러와 마찬가지로 클래스 선언 첫 글자는 대문자입니다. 파일명과 동일하게 작성해야 합니다.

     Line 16: 3.1 절에서 작성한 items 테이블에서 내용을 가져오는 SQL 문을 작성합니다.

     Line 18: 쿼리를 실행합니다. mysql_query($sql)과 동일합니다.

     Line 20: 객체 배열 형태로 쿼리 결과를 생성합니다. mysql_fetch_row($query)와 동일합니다.

     Line 22: 객체 배열 형태로 반환됩니다.



      모델은 필요한 데이터만 반환합니다.


      이제 가져온 todo 목록을 뷰에 어떻게 화면에 출력하는지 알아보겠습니다. todo/application/views/todo/list_v.php 파일을 만들고 다음 내용을 입력합니다.



    * list_v.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8"/>
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
        <title>CodeIgniter</title>
        <!--[if lt IE 9]>
        <script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <link type="text/css" rel='stylesheet' href="/todo/include/css/bootstrap.css" />
    </head>
    <body>
        <div id="main">
            <header id="header" data-role="header" data-position="fixed"><!-- Header Start -->
                <blockquote>
                    <p>만들면서 배우는 CodeIgniter</p>
                    <small>실행 예제</small>
                </blockquote>
            </header<!-- Header End -->
            <nav id="gnb"<!-- gnb start -->
                <ul>
                    <li><a rel="external" href="/todo/index.php/main/lists/">todo 애플리케이션 프로그램</a></li>
                </ul>
            </nav><!-- gnb end -->
            <article id="board_area">
                <header>
                    <h1>Todo 목록</h1>
                </header>
                <table cellspacing="0" cellpadding="0" class="table table-striped">
                    <thead>
                        <tr>
                            <th scope="col">번호</th>
                            <th scope="col">내용</th>
                            <th scope="col">시작일</th>
                            <th scope="col">종료일</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                            foreach ($list as $lt) {
                       ?>
                        <tr>
                            <th scope="row">
                                <?php echo $lt -> id;?>
                            </th>
                            <td>
                                <a rel="external" href="/todo/index.php/main/view/<?php echo $lt -> id; ?>">
                                    <?php echo $lt -> content;?>
                                </a>
                            </td>
                            <td>
                                <time datetime="<?php echo mdate("%Y-%M-%j", human_to_unix($lt -> created_on)); ?>"><?php echo $lt -> created_on;?></time>
                            </td>
                            <td>
                                <time datetime="<?php echo mdate("%Y-%M-%j", human_to_unix($lt -> due_date)); ?>"><?php echo $lt -> due_date;?></time>
                            </td>
                        </tr>
                        <?php
                        }
                       ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <th colspan="4"><a href="/todo/index.php/main/write/" class="btn btn-success">
                                쓰기
                            </a></th>
                        </tr>
                    </tfoot>
                </table>
                <div><p></p></div>
            </article>
            
            <footer>
                <blockquote>
                    <p><a class="azubu" href="http://www.cikorea.net/" target="blank">CodeIgniter 한국 사용자 포럼</a></p>
                    <small>Copyright by <em class="black"><a href="mailto:zhfldi4@gmail.com">Palpit</a></em></small>
                </blockquote>
            </footer>
        </div>
    </body>
    </html>
    cs





     위와 같이 작성 후, localhost/todo/index.php/main/lists/ 에 접속하면 아래와 같이 화면이 나오게 됩니다.


     MySQL에 입력한 데이터가 출력이 되는데, 아래 경우는 MySQL 입력시 인코딩 문제를 처리를 하지 않아서, 한글이 깨져서 나오는 것 같습니다.
















    3.3 보기 만들기

     이번 절에서는 목록에서 todo 내용을 클릭 했을 때 이동하는 todo 내용 보기를 만들어 보겠습니다. main 컨트롤러에 view() 함수의 소스를 추가합니다.


     

     * main.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
    /*
     * todo 컨트롤러
     */
     
    class Main extends CI_Controller 
    {
        function __construct() 
        {
            parent::__construct();
            $this->load->database();
            $this->load->model('todo_m');
            $this->load->helper(array('url''date'));
        }
        
        public function index() 
        {
            $this->lists();
        }
        
        /*
         * todo 목록
         */
        public function lists() 
        {
            $data['list'= $this->todo_m->get_list();
            
            $this->load->view('todo/list_v'$data);
        }
        
        /*
         * todo 조회 
         */
         function view() 
         {
             // todo 번호에 해당하는 데이터 가져오기
             $id = $this->uri->segment(3);
            
            $data['views'= $this->todo_m->get_view($id);
            
            // view 호출
            $this->load->view('todo/todo_v'$data);
         }
    }
     
    /* End of file main.php */
    /* Location: ./application/controllers/main.php */
    cs






     todo_m 모델에 get_view() 함수의 소스를 추가합니다.



    * todo_m.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    <?php
    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
     
    /*
     * todo 모델
     *
     */
     
    class Todo_m extends CI_Model {
        function __construct() {
            parent::__construct();
        }
     
        function get_list() {
            $sql = "SELECT * FROM items";
     
            $query = $this -> db -> query($sql);
     
            $result = $query -> result();
     
            return $result;
        }
     
        /*
         * todo 조회
         */
        function get_view($id) {
            $sql = "SELECT * FROM items WHERE id='" . $id . "'";
     
            $query = $this -> db -> query($sql);
     
            $result = $query -> row();
     
            return $result;
        }
     
    }
     
    /* End of file todo_m.php */
    /* Location: ./application/Models/todo_m.php  */
     
     
    cs

     




     모델은 SQL 문만 조금씩 변동되고 큰 차이가 없습니다.


     todo/application/views/todo/view_v.php 파일을 만들고 다음 내용을 입력합니다.




    * view_v.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8"/>
            <meta name="apple-mobile-web-app-capable" content="yes" />
            <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
            <title>CodeIgniter</title>
            <!--[if lt IE 9]>
            <script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
            <![endif]-->
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
            <link type="text/css" rel='stylesheet' href="/todo/include/css/bootstrap.css" />
        </head>
        <body>
            <div id="main">
                <header id="header" data-role="header" data-position="fixed">
                    <blockquote>
                        <p>
                            만들면서 배우는 CodeIgniter
                        </p>
                        <small>실행 예제</small>
                    </blockquote>
                </header>
                
                <nav id="gnb">
                    <ul>
                        <li>
                            <a rel="external" href="/todo/index.php/main/lists/">todo 애플리케이션 프로그램</a>
                        </li>
                    </ul>
                </nav>
                <article id="board_area">
                    <header>
                        <h1>Todo 조회</h1>
                    </header>
                    <table cellspacing="0" cellpadding="0" class="table table-striped">
                        <thead>
                            <tr>
                                <th scope="col"><?php echo $views -> id;?> 번 할일</th>
                                <th scope="col"><?php echo $views -> created_on;?></th>
                                <th scope="col"><?php echo $views -> due_date;?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <th colspan="3">
                                    <?php echo $views -> content;?>
                                </th>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th colspan="4">
                                    <a href="/todo/index.php/main/lists/" class="btn btn-primary">목록</a>
                                    <a href="/todo/index.php/main/delete/<?php echo $this -> uri -> segment(3); ?>" class="btn btn-danger">삭제</a>
                                    <a href="/todo/index.php/main/write/" class="btn btn-success">쓰기</a>
                                </th>
                            </tr>
                        </tfoot>
                    </table>
                </article>
                
            <footer>
                <blockquote>
                    <p><a class="azubu" href="http://www.cikorea.net/" target="blank">CodeIgniter 한국 사용자 포럼</a></p>
                    <small>Copyright by <em class="black"><a href="mailto:zhfldi4@gmail.com">Palpit</a></em></small>
                </blockquote>
            </footer>        
            </div>
        </body>
    </html>
    cs





     





     





    3.4 쓰기 만들기

     목록, 보기에서의 MVC 패턴은 컨트롤러-모델-뷰에서 끝났습니다. 쓰기는 컨트롤러-뷰-컨트롤러-모델-뷰 형태가 됩니다. 


     main 컨트롤러에 write() 부분 소스를 입력합니다.



    * main.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
    /*
     * todo 컨트롤러
     */
     
    class Main extends CI_Controller 
    {
        function __construct() 
        {
            parent::__construct();
            $this->load->database();
            $this->load->model('todo_m');
            $this->load->helper(array('url''date'));
        }
        
        public function index() 
        {
            $this->lists();
        }
        
        /*
         * todo 목록
         */
        public function lists() 
        {
            $data['list'= $this->todo_m->get_list();
            
            $this->load->view('todo/list_v'$data);
        }
        
        public function view()
        {
            $id = $this->uri->segment(3);
            
            $data['views'= $this->todo_m->get_view($id);
            
            $this->load->view('todo/view_v'$data);
            
        }
        
        /**
         * todo 입력
         */
         
        public function write()
        {
            if ( $_POST )
            {
                // 글쓰기 POST 전송 시
                
                $content = $this->input->post('content', TRUE);
                $created_on = $this->input->post('created_on', TRUE);
                $due_date = $this->input->post('due_date', TRUE);
                
                $this->todo_m->insert_todo($content$created_on$due_date);
                
                redirect('/main/lists/');
                
                exit;
            }
            else 
            {
                // 쓰기 폼 view 호출
                $this->load->view('todo/write_v');        
            }
        }
        
        
    }
     
    /* End of file main.php */
    /* Location: ./application/controllers/main.php */
    cs




      Line 45: 쓰기 함수는 $_POST 의 유무에 따라 if-else 문 분기하여 처리합니다. post 전송이 없을 경우(쓰기 주소로 접속 했을 때)에 else 구문이 실행되면서 입력받는 폼이 화면에 출력됩니다.

      Line 47: 쓰기 화면에서 내용을 채우고 작성 버튼을 클릭하면 if 문 액션이 실행됩니다. $this->input->post('content')는 $_POST['content']와 동일하게 post 변수를 받아주는 역할을 합니다. post 함수의 두 번째 파라미터에 TRUE를 주었을 때 XSS 공격을 막을 수 있게 자동으로 처리합니다.

      Line 55: post 전송받은 데이터를 todo_m 모델의 insert_todo() 함수에 전달하여 데이터베이스에 입력합니다.



     









     내용을 데이터 베이스에 입력하기 위해 todo_m 모델에 다음 소스를 추가합니다.



    * todo_m.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    <?php
    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
     
    /*
     * todo 모델
     *
     */
     
    class Todo_m extends CI_Model {
        function __construct() {
            parent::__construct();
        }
     
        function get_list() {
            $sql = "SELECT * FROM items";
     
            $query = $this -> db -> query($sql);
     
            $result = $query -> result();
     
            return $result;
        }
     
        function get_view($id) {
            $sql = "SELECT * FROM items WHERE id = '" . $id . "'";
     
            $query = $this -> db -> query($sql);
     
            $result = $query -> row();
     
            return $result;
        }
     
        function insert_todo($content$created_on$due_date) {
            $sql = "INSERT INTO items (content, created_on, due_date) VALUES ('" . $content . "', '" . $created_on . "', '" . $due_date . "')";
     
            $query = $this -> db -> query($sql);
        }
     
    }
     
    /* End of file todo_m.php */
    /* Location: ./application/Models/todo_m.php  */
     
     
    cs






     쓰기 모델 함수는 반환 부분은 없고 데이터를 입력한 후 완료 됩니다.


     쓰기 뷰 소스는 다음과 같습니다. todo/application/views/write_v.php 파일을 만들고 아래 코드를 입력합니다.




    * write_v.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
     
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8"/>
            <meta name="apple-mobile-web-app-capable" content="yes" />
            <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
            <title>CodeIgniter</title>
            <!--[if lt IE 9]>
            <script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
            <![endif]-->
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
            <link type="text/css" rel='stylesheet' href="/todo/include/css/bootstrap.css" />
        </head>
        <body>
            <div id="main">
                <header id="header" data-role="header" data-position="fixed">
                    <blockquote>
                        <p>
                            만들면서 배우는 CodeIgniter
                        </p>
                        <small>실행 예제</small>
                    </blockquote>
                </header>
     
                <nav id="gnb">
                    <ul>
                        <li>
                            <a rel="external" href="/todo/index.php/main/lists/">todo 애플리케이션 프로그램</a>
                        </li>
                    </ul>
                </nav>
                <article id="board_area">
                    <header>
                        <h1>Todo 쓰기</h1>
                    </header>
     
                    <form class="form-horizontal" method="post" action="" id="write_action">
                        <fieldset>
                            <div class="control-group">
                                <label class="control-label" for="input01">내용</label>
                                <div class="controls">
                                    <input type="text" class="input-xlarge" id="input01" name="content">
                                    <p class="help-block"></p>
                                </div>
                                <label class="control-label" for="input02">시작일</label>
                                <div class="controls">
                                    <input type="text" class="input-xlarge" id="input02" name="created_on">
                                    <p class="help-block"></p>
                                </div>
                                <label class="control-label" for="input03">종료일</label>
                                <div class="controls">
                                    <input type="text" class="input-xlarge" id="input03" name="due_date">
                                    <p class="help-block"></p>
                                </div>
     
                                <div class="form-actions">
                                    <input type="submit" class="btn btn-primary" id="write_btn" value="작성" />
                                </div>
                            </div>
                        </fieldset>
                    </form>
                </article>
     
                <footer>
                    <blockquote>
                        <p>
                            <a class="azubu" href="http://www.cikorea.net/" target="blank">CodeIgniter 한국 사용자 포럼</a>
                        </p>
                        <small>Copyright by <em class="black"><a href="mailto:zhfldi4@gmail.com">Palpit</a></em></small>
                    </blockquote>
                </footer>
            </div>
        </body>
    </html>
    cs





     









    3.5 삭제 만들기

     삭제는 뷰에서 삭제를 전담하는 컨트롤러의 delete() 함수를 호출하여 데이터베이스에서 내용을 삭제하고 목록으로 이동합니다.


     main 컨트롤러에 다음 내용을 추가합니다.



    * main.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
    /*
     * todo 컨트롤러
     */
     
    class Main extends CI_Controller 
    {
        function __construct() 
        {
            parent::__construct();
            $this->load->database();
            $this->load->model('todo_m');
            $this->load->helper(array('url''date'));
        }
        
        public function index() 
        {
            $this->lists();
        }
        
        /*
         * todo 목록
         */
        public function lists() 
        {
            $data['list'= $this->todo_m->get_list();
            
            $this->load->view('todo/list_v'$data);
        }
        
        public function view()
        {
            $id = $this->uri->segment(3);
            
            $data['views'= $this->todo_m->get_view($id);
            
            $this->load->view('todo/view_v'$data);
            
        }
        
        /**
         * todo 입력
         */
         
        public function write()
        {
            if ( $_POST )
            {
                // 글쓰기 POST 전송 시
                
                $content = $this->input->post('content', TRUE);
                $created_on = $this->input->post('created_on', TRUE);
                $due_date = $this->input->post('due_date', TRUE);
                
                $this->todo_m->insert_todo($content$created_on$due_date);
                
                redirect('/main/lists/');
                
                exit;
            }
            else 
            {
                // 쓰기 폼 view 호출
                $this->load->view('todo/write_v');        
            }
        }
        
        public function delete()
        {
            // 게시물 번호에 해당하는 게시물 삭제
            $id = $this->uri->segment(3);
            
            $this->todo_m->delete_todo($id);
            
            redirect('/main/lists/');
        }
        
    }
     
    /* End of file main.php */
    /* Location: ./application/controllers/main.php */
    cs





     todo_m 모델에 다음 내용을 추가합니다.




    * todo_m.php

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    <?php
    if (!defined('BASEPATH'))
        exit('No direct script access allowed');
     
    /*
     * todo 모델
     *
     */
     
    class Todo_m extends CI_Model {
        function __construct() {
            parent::__construct();
        }
     
        function get_list() {
            $sql = "SELECT * FROM items";
     
            $query = $this -> db -> query($sql);
     
            $result = $query -> result();
     
            return $result;
        }
     
        function get_view($id) {
            $sql = "SELECT * FROM items WHERE id = '" . $id . "'";
     
            $query = $this -> db -> query($sql);
     
            $result = $query -> row();
     
            return $result;
        }
     
        function insert_todo($content$created_on$due_date) {
            $sql = "INSERT INTO items (content, created_on, due_date) VALUES ('" . $content . "', '" . $created_on . "', '" . $due_date . "')";
     
            $query = $this -> db -> query($sql);
        }
        
        function delete_todo($id
        {
            $sql = "DELETE FROM items WHERE id = '".$id."'";
            
            $this->db->query($sql);
        }
     
    }
     
    /* End of file todo_m.php */
    /* Location: ./application/Models/todo_m.php  */
     
     
    cs



     











    3.6 주소 줄이기

     3.5절까지 진행하면서 http://localhost/todo/index.php/main/view/1 과 같은 주소로 웹 페이지에 접속했습니다. 보기 주소와 리스트, 쓰기의 주소를 보면 하는 역할은 없는 것 같은데 반복적으로 들어있는 주소가 있습니다. 


     index.php 입니다. 프레임워크의 특성이긴 합니다만 사용자 입장에서는 별로 의미도 없는데 더 입력해야 합니다.


     직관적이고 깔끔한 url을 만들기위해 아래 절차를 진행하도록 하겠습니다.


     


     먼저, 주소를 바꿔주는 개념이라 아파치의 모듈 중 하나인 mod_rewrite 모듈을 사용합니다.


     보통 기본으로 설정되어 있으나 해당 위치를 확인해 봅니다. 아파치 설정 파일에서 해당 라인이 주석으로 처리됐을 수도 있으니 아래 파일을 열어서 해당 라인을 찾아 확인합니다.



    * xampp/apache/conf/httpd.conf


     




     mod_rewrite.so 라인에 주석처리가 되어 있다면 주석을 삭제하고 아파치를 다시 시작합니다. 다시 시작하지 않으면 설정을 바꾼 것이 적용되지 않습니다.



     다음으로 또 확인해야할 것이 있는데 서버 디렉터리의 AllowOverride 설정입니다.


     아래 부분처럼 AllowOvrride 부분을 All로 바꿔주시길 바랍니다.


     








     위 두 가지 설정을 확인하고 아파치 서버를 재시작했다면 이제 서버쪽 준비는 끝났습니다.


     CodeIgniter의 설정파일과 .htaccess 파일을 수정하는 방법을 알아봅니다.


     아래 경로의 config.php 파일을 에디터로 열고 '$config['index_page']' 라인을 찾습니다. 기본 값은 'index.php' 입니다. 


     아래 처럼 수정한 뒤 저장합니다.


     

    * config.php


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    /*
    |--------------------------------------------------------------------------
    | Index File
    |--------------------------------------------------------------------------
    |
    | Typically this will be your index.php file, unless you've renamed it to
    | something else. If you are using mod_rewrite to remove the page set this
    | variable so that it is blank.
    |
    */
    $config['index_page'] = '';
    cs




     에디터에서 todo 디렉터리에 .htaccess 파일을 만듭니다. 다음 소스 내용을 입력하고 저장합니다.



    * xampp/htdocs/todo/.htaccess

     

    1
    2
    3
    4
    5
    6
    7
    8
    <IfModule mod_rewrite.c>
        RewriteEngine On
     RewriteBase /
     RewriteCond $1 !^(index\.php|images|captcha|data|application|include|uploads|robots\.txt)
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule ^(.*)$ /todo/index.php/$1 [L]
    </IfModule>
    cs



     저장 후, localhost/todo/main/lists/ 를 입력합니다.


     







     


    * 이 포스트는 서적 '만들면서 배우는 CodeIgniter 프레임워크'를 참고하여 작성하였습니다.

    댓글

Designed by Tistory.