LinkedNestBlog

Codeigniter Library

by 이진원Dev
Codeigniter Library

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

  • 설명
    • 라이브러리는 재활용 가능성이 있는 로직을 재활용하기 좋은 형태로 만들어둔 것.
    • CI에서는 웹 개발에서 자주 이용되는 로직들을 내장(Core) 라이브러리로 제공.
      • 내장 라이브러리를 확장(extend)해서 필요에 따라 수정해서 사용할 수 있고
    • 직접 라이브러리를 만들 수도 있다.
  • 어떻게 사용?
    • 형태
      • 라이브러리의 로드
        $this->load->library('some_class');
      • 로드 후 클래스 및 메서드의 사용
        $this->some_class->some_method
  • Form Validation을 통한 Library 사용 예제
    • 소스코드
      • model/article_model.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
        <?php
        class Article_model extends CI_Model {
         
            // 생성자
            function __construct(){
                parent::__construct();
            }
         
            // select list 수행
            public function getArticles(){
                // 질의 : $this -> db -> query('SELECT * FROM article')
                // result() : 결과값을 어떤 방식으로 가져울 거내는 것을 결정
                // * return 값이 하나이면 row를 사용.
                return $this -> db -> query('SELECT * FROM article') -> result();        
            }
         
            // select row 수행
            public function getArticle($id){
                $this -> db -> select('id');
                $this -> db -> select('title');
                $this -> db -> select('content');
                $this -> db -> select('UNIX_TIMESTAMP(create_date) as create_date');        
                // 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();
            }
         
            // insert 수행
            public function add($title, $content){
                $this -> db -> set('create_date', 'NOW()', false);
                $this -> db -> insert('article', array('title' => $title, 'content' => $content));
                return $this -> db -> insert_id();
            }
        }
        ?>
        cs
      • controller/article.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
        <?php
        defined('BASEPATH') OR exit('No direct script access allowed');
         
        //Controller : Url 을 mapping 하는 역할
        class Article extends CI_Controller {
         
            // 생성자
            function __construct(){
                parent::__construct();    
                // database library  로드
                $this -> load -> database();
                // model 로드
                $this -> load -> model('article_model');
            }
         
         
            // URL : http://127.0.0.1:8080/index.php/topic
            public function index()
            {
                $this -> _header();
                $this -> load ->view('article/main');
                $this -> load ->view('article/footer');
            }
         
            // URL : http://127.0.0.1:8080/index.php/topic/get/3
            // Parameter : $id = 3
            public function get($id){
                $this -> _header();
                // 특정 article 조회
                $article = $this -> article_model -> getArticle($id);    
                // helper의 사용
                $this->load->helper(array('url', 'HTML', 'korean'));
                // article view
                $this -> load -> view('article/get', array('article'=>$article));
                $this -> load -> view('article/footer');
            }
            
            // description : header에 출력되는, 공통 사항들을 별도의 메서드로 분리함.
            function _header(){
                $this -> load ->view('article/header');
                // article list 조회
                $article_list = $this -> article_model -> getArticles();
                // article list view 
                $this -> load -> view('article/article_list', array('articles' => $article_list));
            }
         
            // description : form validation을 사용
            function add(){
                $this -> _header();
                // library load
                $this -> load -> library('form_validation');
                // class의 method 사용
                $this -> form_validation -> set_rules('title', '제목', 'required');
                $this -> form_validation -> set_rules('content', '내용', 'required'); 
         
                if($this -> form_validation -> run() == FALSE){
                    // validation 결과가 false이면 write 화면으로
                    $this -> load -> view('article/add');
                }else{
                    // validation 결과가 true이면 
                    // 1. DB 입력 수행
                    $article_id = $this -> article_model -> add($this -> input -> post('title'), $this -> input -> post('content'));
                    // 2. get(view) 화면으로  redirect
                    $this -> load ->helper('url');
                    redirect('/article/get/'.$article_id);
                }
                $this -> load -> view('footer');
            }
        }
         
        cs
      • view/add.php
        1
        2
        3
        4
        5
        6
        <form action="/article/add" method="post" class="span10">
            <?php echo validation_errors(); ?>
            <input type="text" name="title" class="span12" placeholder="제목" />
            <input type="text" name="content" class="span12" placeholder="내용" />
            <input type="submit" class="btn"/>
        </form>
        cs
      • view/get.php
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        <div class="span10">
            <article>
                <h1><?=$article -> title?></h1>
                <div><?=$article -> content?></div>
                <div><?=kdate($article -> create_date)?></div>
                <?=auto_link($article -> content)?>
            </article>
            <div>
                <a href="/article/add" class="btn">추가</a>
            </div>
        </div>
        cs
Codeigniter Library · LinkedNest Blog