모델 업그레이드
문서
변경된 사항
CI4 모델은 자동 데이터베이스 연결, 기본 CRUD, 모델 내 유효성 검사, 자동 페이지네이션을 포함한 훨씬 더 많은 기능을 갖추고 있습니다.
CodeIgniter 4에 네임스페이스가 추가되었으므로, 모델을 네임스페이스를 지원하도록 변경해야 합니다.
업그레이드 가이드
먼저 모든 모델 파일을 app/Models 폴더로 이동하십시오.
PHP 여는 태그 바로 뒤에 다음 줄을 추가하십시오:
namespace App\Models;namespace App\Models;줄 아래에 다음 줄을 추가하십시오:use CodeIgniter\Model;extends CI_Model을extends Model로 교체하십시오.protected $table속성을 추가하고 테이블 이름을 설정하십시오.protected $allowedFields속성을 추가하고 삽입/업데이트를 허용할 필드 이름 배열을 설정하십시오.CI3의
$this->load->model('x');대신, 이제 컴포넌트의 네임스페이스 규칙을 따라$this->x = new X();를 사용합니다. 또는model()함수를 사용할 수 있습니다:$this->x = model('X');
모델 구조에 하위 디렉토리를 사용하는 경우 이에 맞게 네임스페이스를 변경해야 합니다. 예: application/models/users/user_contact.php에 위치한 버전 3 모델이 있다면, 네임스페이스는 namespace App\Models\Users;여야 하고 버전 4의 모델 경로는 app/Models/Users/UserContact.php와 같아야 합니다.
CI4의 새 모델에는 많은 내장 메서드가 있습니다. 예를 들어, find($id) 메서드를 사용하면 기본 키가 $id와 같은 데이터를 찾을 수 있습니다. 데이터 삽입도 이전보다 쉬워졌습니다. CI4에는 insert($data) 메서드가 있습니다. 선택적으로 이러한 내장 메서드를 모두 활용하여 코드를 새 메서드로 마이그레이션할 수 있습니다.
이러한 메서드에 대한 자세한 정보는 CodeIgniter 모델 사용하기에서 확인할 수 있습니다.
코드 예제
CodeIgniter 버전 3.x
경로: application/models:
<?php
class News_model extends CI_Model
{
public function set_news($title, $slug, $text)
{
$data = array(
'title' => $title,
'slug' => $slug,
'text' => $text,
);
return $this->db->insert('news', $data);
}
}
CodeIgniter 버전 4.x
경로: app/Models:
<?php
namespace App\Models;
use CodeIgniter\Model;
class NewsModel extends Model
{
// Sets the table name.
protected $table = 'news';
public function setNews($title, $slug, $text)
{
$data = [
'title' => $title,
'slug' => $slug,
'text' => $text,
];
// Gets the Query Builder for the table, and calls `insert()`.
return $this->builder()->insert($data);
}
}
위 코드는 CI3에서 CI4로의 직접 변환입니다. 모델에서 쿼리 빌더를 직접 사용합니다. 쿼리 빌더를 직접 사용할 때는 CodeIgniter 모델의 기능을 사용할 수 없다는 점에 유의하십시오.
CodeIgniter의 모델 기능을 사용하려면 코드는 다음과 같습니다:
<?php
namespace App\Models;
use CodeIgniter\Model;
class NewsModel extends Model
{
// Sets the table name.
protected $table = 'news';
// Sets the field names to allow to insert/update.
protected $allowedFields = ['title', 'slug', 'text'];
public function setNews($title, $slug, $text)
{
$data = [
'title' => $title,
'slug' => $slug,
'text' => $text,
];
// Uses Model's`insert()` method.
return $this->insert($data);
}
}