LinkedNestBlog

Codeigniter Model

by 이진원Dev
Codeigniter Model


Ref.] https://opentutorials.org/course/697/3827

  • 설명
    • 데이터를 다루는 logic을 Model로 모아서 데이터와 view를 격리시키는 것.
    • 장점 :
      • 코드 관리의 편의성이 높아짐
      • DBMS를 다른 타입으로 교체가 용이
  • 설정
    • 데이터베이스 설정
      • database.php 수정
        • 경로
          • /Applications/mampstack-5.6.20-0/apache2/htdocs/application/config
        • 수정 내용
          $db['default'] = array(
          'dsn' => '',
          'hostname' => '127.0.0.1',
          'username' => 'root',
          'password' => '',
          'database' => 'php_exercise',
          'dbdriver' => 'mysqli',
          'dbprefix' => '',
          'pconnect' => FALSE,
          'db_debug' => (ENVIRONMENT !== 'production'),
          'cache_on' => FALSE,
          'cachedir' => '',
          'char_set' => 'utf8',
          'dbcollat' => 'utf8_general_ci',
          'swap_pre' => '',
          'encrypt' => FALSE,
          'compress' => FALSE,
          'stricton' => FALSE,
          'failover' => array(),
          'save_queries' => TRUE
          );
    • 데이터베이스 라이브러리 로드
      1. autoload의 사용
        • 경로
          /Applications/mampstack-5.6.20-0/apache2/htdocs/application/config
        • application/autoload.php의
          $autoload['libraries'] = array('database');
          으로 수정
      2. Controller에서 database 로드
        $this -> load -> database();
    • 모델 파일의 사용
      • Model의 생성
        • 소스코드
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          <?php
          class Article_model extends CI_Model {
              // 생성자
              function __construct(){
                  parent::__construct();
              }
           
              public function getArticles(){
                  // 질의 : $this -> db -> query('SELECT * FROM article')
                  // result() : 결과값을 어떤 방식으로 가져울 거내는 것을 결정
                  // * return 값이 하나이면 row를 사용.
                  return $this -> db -> query('SELECT * FROM article') -> result();
              }
          }
          ?>
          cs
      • Controller에서의 Model 호출
        • 소스코드
          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
          <?php
          defined('BASEPATH') OR exit('No direct script access allowed');
           
          //Controller : Url 을 mapping 하는 역할
          class Topic extends CI_Controller {
           
              // http://127.0.0.1:8080/index.php/topic
              public function index()
              {
                  #echo 'topic page';
                  // database library  로드
                  $this -> load -> database();    
                  // model 로드
                  $this -> load -> model('article_model');
                  // model 안에 있는 메서드를 호출
                  $data = $this -> article_model -> getArticles();
                  // 데이터 확인
                  foreach($data as $entry){
                      var_dump($entry);
                  }
           
                  $this -> load ->view('header');
                  $this -> load ->view('topic');
                  $this -> load ->view('footer');
              }
           
              // http://127.0.0.1:8080/index.php/topic/get/3
              // $id = 3
              public function get($id){
                  #echo "topic".$id;
                  $this -> load ->view('header');
                  $this -> load ->view('get', array('id'=>$id));
                  $this -> load ->view('footer');
              }
          }
           
          cs
    • 호출시 
      • URL : http://127.0.0.1:8080/index.php/topic
      • 결과 : 
        object(stdClass)#19 (4) { ["id"]=> string(1) "1" ["title"]=> string(6) "111222" ["content"]=> string(10) "1111122222" ["create_date"]=> string(19) "2016-04-19 15:38:17" } this is topic page!
  • 예제 : 파라미터의 사용
    • url : http://127.0.0.1:8080/index.php/topic/get/1
    • 소스코드
      • Controller
        • get meethod를 수정
          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
          <?php
          defined('BASEPATH') OR exit('No direct script access allowed');
           
          //Controller : Url 을 mapping 하는 역할
          class Topic extends CI_Controller {
           
              // http://127.0.0.1:8080/index.php/topic
              public function index()
              {
                  #echo 'topic page';
                  // database library  로드
                  $this -> load -> database();    
                  // model 로드
                  $this -> load -> model('article_model');
                  // model 안에 있는 메서드를 호출
                  $data = $this -> article_model -> getArticles();
                  // 데이터 확인
                  /*
                  foreach($data as $entry){
                      var_dump($entry);
                  }
                  */
                  $this -> load ->view('header');
                  $this -> load ->view('topic', array('articles'=> $data));
                  $this -> load ->view('footer');
              }
           
              // http://127.0.0.1:8080/index.php/topic/get/3
              // $id = 3
              public function get($id){
                  #echo "topic".$id;
                  $this -> load -> database();
                  $this -> load -> model('article_model');
                  $article = $this -> article_model -> getArticle($id);    
           
                  $this -> load ->view('header');
                  $this -> load ->view('get', array('article'=>$article));
                  $this -> load ->view('footer');
              }
          }
           
          cs
      • Model
        • getArticle method를 생성
          1
          2
          3
          4
          5
          6
          7
          8
          9
          10
          11
          12
          13
          14
          15
          16
          17
          18
          19
          20
          21
          22
          23
          24
          <?php
          class Article_model extends CI_Model {
              // 생성자
              function __construct(){
                  parent::__construct();
              }
           
              public function getArticles(){
                  // 질의 : $this -> db -> query('SELECT * FROM article')
                  // result() : 결과값을 어떤 방식으로 가져울 거내는 것을 결정
                  // * return 값이 하나이면 row를 사용.
                  return $this -> db -> query('SELECT * FROM article') -> result();
              }
           
              public function getArticle($id){
                  // active record query 방식
                  $active_record_sql = $this -> db -> get_where('article', array('id' => $id));
                  // 일반적인 query 방식
                  // $nomal_sql = $this -> db -> query('SELECT * FROM article WHERE id = '.$id);
                  // return 
                  return  $active_record_sql -> row();
              }
          }
          ?>
          cs
          active record를 이용하면 표준 sql을 이용할 수 있어 이식성이 좋은 형태의 어플리케이션을 만들 수 있고, 프로그래밍적으로 쿼리를 생성 할 수 있어 sql 문자열을 직접 다루는 수고를 덜 수 있다.
          Question : JOIN을 사용해서 복수의 테이블을 사용하는 경우에는??? 
      • view
        • get.php 파일의 수정
          1
          2
          3
          4
          <article>
              <h1><?=$article -> title?></h1>
              <div><?=$article -> content?></div>
          </article>
          cs
    • 화면 상에서의 출력

      111222

      1111122222