Codeigniter Model
Codeigniter Model
Ref.] https://opentutorials.org/course/697/3827
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
);
- 경로
- database.php 수정
- 데이터베이스 라이브러리 로드
- autoload의 사용
- 경로
/Applications/mampstack-5.6.20-0/apache2/htdocs/application/config
- application/autoload.php의
$autoload['libraries'] = array('database');으로 수정
- 경로
- Controller에서 database 로드
$this -> load -> database();
- autoload의 사용
- 모델 파일의 사용
- Model의 생성
- 소스코드
123456789101112131415<?phpclass 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 호출
- 소스코드
123456789101112131415161718192021222324252627282930313233343536<?phpdefined('BASEPATH') OR exit('No direct script access allowed');//Controller : Url 을 mapping 하는 역할class Topic extends CI_Controller {// http://127.0.0.1:8080/index.php/topicpublic 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 = 3public function get($id){#echo "topic".$id;$this -> load ->view('header');$this -> load ->view('get', array('id'=>$id));$this -> load ->view('footer');}}
cs
- 소스코드
- Model의 생성
- 호출시
- 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를 수정
1234567891011121314151617181920212223242526272829303132333435363738394041<?phpdefined('BASEPATH') OR exit('No direct script access allowed');//Controller : Url 을 mapping 하는 역할class Topic extends CI_Controller {// http://127.0.0.1:8080/index.php/topicpublic 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 = 3public 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
- get meethod를 수정
- Model
- getArticle method를 생성
active record를 이용하면 표준 sql을 이용할 수 있어 이식성이 좋은 형태의 어플리케이션을 만들 수 있고, 프로그래밍적으로 쿼리를 생성 할 수 있어 sql 문자열을 직접 다루는 수고를 덜 수 있다.123456789101112131415161718192021222324<?phpclass 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);// returnreturn $active_record_sql -> row();}}?>
cs Question : JOIN을 사용해서 복수의 테이블을 사용하는 경우에는???
- getArticle method를 생성
- view
- get.php 파일의 수정
1234<article><h1><?=$article -> title?></h1><div><?=$article -> content?></div></article>
cs
- get.php 파일의 수정
- Controller
- 화면 상에서의 출력
111222
1111122222