DEV/🔥 CODEIGNITOR

Codeignitor 기본팩

개발을 하게 되. 2022. 5. 17. 09:27

 

 

Codeigniter

그동안 한주 노션에 기록했던 기록물들을 이제서야 올린다.

 

CodeIgniter 소개 - 생활코딩

Framework 프래임워크란 에플리케이션을 구현 할 때 공통되는 부분과 에플리케이션 특화된 부분을 구분해서 공통되는 부분은 미리 만들어진 체계를 이용하고, 에플리케이션 특화된 부분은 직접

opentutorials.org

PHP 기반으로 오픈소스이고, 무료로 사용 할 수 있는 프레임워크이다.

프레임워크 중의 하나고, 빠르고 MVC(Model, View, Controller) 모델을 지원

 

Controller 🎮

만약 아래와 같은 페이지로 접근했을 때 페이지를 출력하기 위한 방법에 대해서 알아보자.

Controller 생성

콘트롤러의 이름에 의해서 URL이 결정된다는 점이고,

콘트롤러를 통해서 웹페이지를 화면에 출력 할 수 있다는 점이다

**http://ooo2.org/index.php/topic**

만약 index.php 뒤에 topic이라는 경로를 사용하고 싶다면 controllers 디렉토리 밑에 topic.php라는 이름의 파일을 생성해야 한다.

controllers

┖ topic.php

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

class Topic extends CI_Controller {
    function index(){
        echo '
	        <!DOCTYPE html>
	        <html>
	            <head>
	                <meta charset="utf-8"/>
	            </head>
	            <body>
	                토픽 메인 페이지
	            </body>
	        </html>
				';
    }

그리고 이 파일은 CI_Controller이라는 클래스를 상속한 Topic라는 이름을 가지고 있어야 한다.

그리고 index라는 이름의 메소드를 구현하면 CI는 이 메소드를 호출한다. 이것은 코드이그나이터 약속임. 

 

근데 또 topic 뒤에 또 다른 경로 설정하고싶다면?

**http://ooo2.org/index.php/topic/get/1**

 

controllers

┖ topic.php 파일에서 function get($id)를 설정하면 되는 것임

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

class Topic extends CI_Controller {
    function index(){
        echo '
	        <!DOCTYPE html>
	        <html>
	            <head>
	                <meta charset="utf-8"/>
	            </head>
	            <body>
	                토픽 메인 페이지
	            </body>
	        </html>
				';
    }

		**function get($id){
		        echo '
		        <!DOCTYPE html>
		        <html>
		            <head>
		                <meta charset="utf-8"/>
		            </head>
		            <body>
		                토픽 '.$id.'
		            </body>
		        </html>
		        ';
		    }
		}
		?>**

View 🎨

뷰란 화면상에 출력되는 내용을 의미한다

CodeIgniter를 이용해서 화면에 내용을 출력하기 위해서는 Controller에서 echo를 하는 것도 방법이지만, View 안에서 UI와 관련된 코드를 작성하는 것이 바람직. 

 

View의 생성

application

┖ views

┖ 뷰 파일.php

 

view는 쉽게 말해서 html/css/javascript와 같은 코드를 관리하는 방법

application 디렉토리 하위에 views 라는 디렉토리 아래에 php 파일을 생성하고 여기에 웹페이지를 저장 .

앞선 수업에서는 html 코드를 출력하기 위해서 application/controllers/topic.php 파일에 만든 메소드에서 echo 를 호출하고 있었다.

하지만 이것을 $this->load->view 라는 구문으로 대체했는데,

 

>> Controller 수정

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

class Topic extends CI_Controller {

    function index(){
        $this->load->view('head');
        $this->load->view('main');
        $this->load->view('footer');
    }

    function get($id){
        $this->load->view('head');
        $this->load->view('get', array('id'=>$id));
        $this->load->view('footer');
    }
}
?>

view의 인자로 head, main, footer를 사용하고 있다.

이것은 head.php, main.php, footer.php 파일을 로드하겠다는 의미인데,

이 파일들은 application/views/ 디렉토리 아래에 위치하도록 약속되어 있다.

 

application

┖ views

┖ head.php

┖ main.php

get.php

┖ footer.php

┖ head.php

 

<!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8"/>
            </head>
            <body>

┖ main.php

토픽페이지

get.php

토픽 <? $id ?>

┖ footer.php

 

Model 🦴

View가 표현을 담당한다면 Model은 데이터를 담당한다.

여기서 데이터란 주로 데이터베이스를 의미한다.

즉 데이터를 다루는 로직을 모델에 모아둬서 데이터와 뷰를 격리 시키는 것이다.

결국, 코드 관리의 편의성을 높일 수 있고, 향후 데이터베이스를 다른 타입으로 교체가 용이하다.

 

데이터베이스 설정

application

┖ config

   ┖ database.php

 

database.php 속성들

  • hostname : 데이터베이스 서버의 주소 (localhost는 PHP와 같은 머신을 의미)
  • username : 데이터베이스 사용자의 이름
  • password : 데이터베이스 비밀번호
  • database : 데이터베이스 명
  • dbdriver : 데이터베이스의 종류로 지원되는 드라이브의 목록은 system/database/drivers 디렉토리명을 참고한다.

 

0.데이터베이스 라이브러리 로드

 

데이터베이스를 사용하기 위해서는 우선 데이터베이스 라이브러리를 로드해야 한다.

이 라이브러리는 CI(코드이그나이터) 에서 데이터베이스를 제어 하는 방법을 제공한다.

이것을 로드하는 방법은 두가지다. (topic.php 예제 참고데이터베이스 Quick Start 참고)

  1. application/config/autoload.php 파일의 $autoload['libraries'] 배열에 'database'를 추가한다.
  2. controller 내에서 $this->load->database()를 호출한다.

설정과 라이브러리 로드가 끝났다면 이제 모델 클래스 파일을 생성해야 한다.

 

1.모델 파일의 사용

 

application

┖ models

    ┖ 모델명_model.php

파일은 CI_Model 클래스를 상속 받아야 하고

클래스 명은 '대문자로 시작하는 모델명_model' 이어야 한다.

모델 내에서 쿼리를 사용하기 위해서는 $this->db를 이용한다.

 

예를들어 topic 테이블의 내용을 조회한다면 아래와 같이하면 된다.

$this->db->query("SELECT * FROM topic")

쿼리의 결과를 가져오려면 ?

$this->db->query("SELECT * FROM topic")->result();

 

2.쿼리 결과 생성

result()는 쿼리의 결과를 가져오는 방법을 정한다.

만약, 연관배열의 형태로 데이터를 가져오고 싶다면 result_array()를 사용

결과가 한행이라면 row()를 사용한다.

Generating Query Results : CodeIgniter User Guide

쿼리결과 생성 (Query Result)

 

Active Record

Active Record는 좀 더 프로그래밍적으로 데이터베이스를 제어하는 방법이다.

예를들어 topic 테이블에서 id 값이 3인 행을 조회하고 싶다면 아래와 같이 한다.

$this->db->get_where('topic', array('id'=>$topic_id))->row();

Active Record를 이용하면 표준 SQL을 이용할 수 있어서 에플리케이션을 좀 더 이식성 좋은 형태로 만들 수 있고, 프로그래밍적으로 쿼리를 생성 할 수 있기 때문에 SQL 문자열을 직접 다루는 수고를 덜 수 있다. = 일종의 Django ORM

 

모델 사용

model은 데이터를 가져오는 로직을 메소드로 정의하고, (GET POST CREAT UPDATE)

이 메소드는 controller를 통해서 사용된다. 아래는 모델을 사용하는 방법이다.

 

모델 로드

모델을 사용하기 위해서는 모델을 로드해야 하는데 아래의 형식을 사용한다.

형식 : $this->load->model('소문자로된 모델 클래스 명');

예제 : $this->load->model('topic_model');

 

모델 호출

이제부터는 아래의 형식으로 로드한 모델의 API를 호출 할 수 있다.

형식 : 모델 클래스 명'->'메소드 명'

예제 : $topics = $this->topic_model->gets();

예제

 

1. 데이터베이스 기본값 설정

application

┖ config

   ┖ database.php

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

$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '*****';
$db['default']['database'] = 'opentutorials';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$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;

2. controllers

   ┖ topic.php 설정

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

# url :  ~~~.com/topic
class Topic extends CI_Controller {
    function __construct()
    {       
        parent::__construct();
        # 데이터 베이스 로드 및 모델 로드. 
				$this->load->database();
        $this->load->model('topic_model');
    }

    function index(){        
        $this->load->view('head');

				#Controller로 디비에서 가져옴
        $topics = $this->topic_model->gets();

        $this->load->view('topic_list', array('topics'=>$topics));
        $this->load->view('main');
        $this->load->view('footer');
    }
    function get($id){        
        $this->load->view('head');
        $topics = $this->topic_model->gets();
        $this->load->view('topic_list', array('topics'=>$topics));
        $topic = $this->topic_model->get($id);
        $this->load->view('get', array('topic'=>$topic));
        $this->load->view('footer');
    }
}
?>

 

3. models

   ┖ topic_model.php

<?php
class Topic_model extends CI_Model {
 
    function __construct()
    {       
        parent::__construct();
    }
 
    function gets(){
        return $this->db->query("SELECT * FROM topic")->result();
    }
 
    function get($topic_id){
        return $this->db->get_where('topic', array('id'=>$topic_id))->row();
    }
}

4. views

   ┖ get.php

<article>
    <h1><?=$topic->title?></h1>
    <div>
        <?=$topic->description?>
    </div>
</article>

application

┖ views

┖ head.php

┖ main.php

┖ get.php

┖ topic_list.php

┖ footer.php

┖ main.php

토픽메인

┖ topic_list.php

<ul>
	<?php
		foreach($topics as $entry){
	?>
			<li><a href="/index.php/topic/get/<?=$entry->id?>"><?=$entry->title?></a></li>
	<?php
	}
	?>
</ul>