CodeIgniter란 PHP기반의 프레임워크이고 빠르고 MVC모델을 지원한다.**
Model : DB에 접속해서 DB의 내용을 가져오거나 변경할 때 사용하는 것
view : 화면에 무엇인가 표시하는 것과 관련되어 있는 것
Controller : 어떤 데이터를 받아 가공하여 view에 전달하는 것
홈페이지 : CodeIgniter
CodeIgniter 한국 커뮤니티 : Community
하단 링크를 통해 설치
설치
도메인 주소/index.php/topic
이고 Controller 디렉토리 밑에 topic.php
을 생성하면 코드이그나이터 내부적으로 1대1로 매칭이 된다.topic.php
파일 내부에서 클래스 네임은 topic으로 사용해야한다.도메인 주소/index.php/topic
이면 topic 클래스 내부의 index 메소드를 호출된다.도메인 주소/index.php/topic/get/2
이면 topic 클래스 내부의 get 메소드를 호출하고 파라미터 인자를 정의해준다면 $id 변수에는 2가 출력된다.topic.php
class Topic extends CI_Controller {
public function index() {
echo '토픽 페이지';
}
public function get($id) {
echo '토픽 '.$id;
}
}
<?=$id?>
형태로 사용topic.php
class Topic extends CI_Controller {
public function index() {
$this->load->view('topic');
}
public function get($id) {
$data = array('id'=>$id);
$this->load->view('get',$data);
}
}
database설정파일은 서버에 접속할 수 있는 기밀정보가 포함되어 있기때문에 버전관리에 포함시키면 안된다. gitignore에 추가시키는 방법도 있다.
데이터베이스 라이브러리 로드
데이터베이스를 사용하기 위해 라이브러리를 로드하는 방법 2가지
- autoload.php파일의 $autoload['libraries'] = array('database');
형태로 배열에 'database'를 추가
- controller 내부 파일에서 $this->load->database()
를 호출
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Topic extends CI_Controller { //동일한 메소드를 호출할 때
function __construct()
{
parent::__construct();
$this->load->database(); //controller에서 DB 라이브러리 호출
$this->load->model('topic_model'); // 모델 디렉토리 밑에 'topic_model.php'파일을 php가 읽어서 Topic_model class를 로드
}
function index(){
$this->load->view('head');
$topics = $this->topic_model->gets(); // 해당 오브젝트에 접근해서 gets 메소드를 호출
$this->load->view('topic_list', array('topics'=>$topics)); //가져온 data를 두번째 인자에 배열형태로 뷰에 전달
$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');
}
}
?>
<?php
class Topic_model extends CI_Model {
function __construct()
{
parent::__construct();
}
function gets(){
return $this->db->query("SELECT * FROM topic")->result(); // SQL문을 통해 가져온 data를 객체형태로 리턴
}
function get($topic_id){
return $this->db->get_where('topic', array('id'=>$topic_id))->row(); // 결과가 한행이라면 row 메소드를 사용
}
}
<article>
<h1><?=$topic->title?></h1>
<div>
<?=$topic->description?>
</div>
</article>
토픽메인
<ul>
<?php
foreach($topics as $entry){
?>
<li><a href="/index.php/topic/get/<?=$entry->id?>"><?=$entry->title?></a></li>
<?php
}
?>
</ul>