모델¶
모델은 보다 전통적인 MVC 방식을 사용하려는 사람들을 위해 선택적으로 사용 가능합니다.
모델이란 무엇인가?¶
모델은 데이터베이스의 정보를 처리하도록 설계된 PHP 클래스입니다. 예를 들어 CodeIgniter를 사용하여 블로그를 관리한다고 가정해 보겠습니다. 블로그 데이터를 삽입, 업데이트, 검색하는 함수가 포함된 모델 클래스가 있을 수 있습니다. 다음은 그러한 모델 클래스의 예시입니다:
class Blog_model extends CI_Model {
public $title;
public $content;
public $date;
public function get_last_ten_entries()
{
$query = $this->db->get('entries', 10);
return $query->result();
}
public function insert_entry()
{
$this->title = $_POST['title']; // please read the below note
$this->content = $_POST['content'];
$this->date = time();
$this->db->insert('entries', $this);
}
public function update_entry()
{
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->date = time();
$this->db->update('entries', $this, array('id' => $_POST['id']));
}
}
참고
위 예시의 메소드는 Query Builder 데이터베이스 메소드를 사용합니다.
참고
이 예시에서는 단순성을 위해 $_POST 를 직접 사용합니다. 이는 일반적으로 좋지 않은
관행이며, 보다 일반적인 방법은 Input 라이브러리
$this->input->post('title') 를 사용하는 것입니다.
모델의 구조¶
모델 클래스는 application/models/ 디렉터리에 저장됩니다. 이러한 유형의 구성을 원한다면 서브 디렉터리 내에 중첩할 수 있습니다.
모델 클래스의 기본 프로토타입은 다음과 같습니다:
class Model_name extends CI_Model {
}
여기서 Model_name 은 클래스의 이름입니다. 클래스 이름은 반드시 첫 번째 글자가 대문자여야 하고 나머지는 소문자여야 합니다. 기본 Model 클래스를 확장해야 합니다.
파일 이름은 클래스 이름과 일치해야 합니다. 예를 들어 다음과 같은 클래스가 있다면:
class User_model extends CI_Model {
}
파일 이름은 다음과 같습니다:
application/models/User_model.php
모델 로드¶
모델은 일반적으로 컨트롤러 메소드 내에서 로드되고 호출됩니다. 모델을 로드하려면 다음 메소드를 사용합니다:
$this->load->model('model_name');
모델이 서브 디렉터리에 있는 경우 models 디렉터리에서 상대 경로를 포함하세요. 예를 들어 application/models/blog/Queries.php 에 모델이 있다면 다음을 사용하여 로드합니다:
$this->load->model('blog/queries');
로드되면 클래스와 동일한 이름을 가진 오브젝트를 사용하여 모델 메소드에 접근합니다:
$this->load->model('model_name');
$this->model_name->method();
모델을 다른 오브젝트 이름에 할당하려면 로딩 메소드의 두 번째 매개변수를 통해 지정할 수 있습니다:
$this->load->model('model_name', 'foobar');
$this->foobar->method();
다음은 모델을 로드하고 뷰를 제공하는 컨트롤러의 예시입니다:
class Blog_controller extends CI_Controller {
public function blog()
{
$this->load->model('blog');
$data['query'] = $this->blog->get_last_ten_entries();
$this->load->view('blog', $data);
}
}
모델 자동 로드¶
애플리케이션 전반에 걸쳐 특정 모델이 필요하다면 시스템 초기화 중에 자동 로드하도록 CodeIgniter에 지시할 수 있습니다. application/config/autoload.php 파일을 열고 모델을 autoload 배열에 추가하여 이를 수행합니다.
데이터베이스 연결¶
모델이 로드될 때 데이터베이스에 자동으로 연결되지 않습니다. 다음 연결 옵션을 사용할 수 있습니다:
여기에 설명된 표준 데이터베이스 메소드를 사용하여 컨트롤러 클래스 또는 모델 클래스 내에서 연결할 수 있습니다.
세 번째 매개변수에 TRUE(불리언)를 전달하여 모델 로딩 메소드가 자동 연결하도록 지시할 수 있으며, 데이터베이스 설정 파일에 정의된 연결 설정이 사용됩니다:
$this->load->model('model_name', '', TRUE);
세 번째 매개변수에 데이터베이스 연결 설정을 수동으로 전달할 수 있습니다:
$config['hostname'] = 'localhost'; $config['username'] = 'myusername'; $config['password'] = 'mypassword'; $config['database'] = 'mydatabase'; $config['dbdriver'] = 'mysqli'; $config['dbprefix'] = ''; $config['pconnect'] = FALSE; $config['db_debug'] = TRUE; $this->load->model('model_name', '', $config);