본문 바로가기
Programming/PHP

[코드이그나이터] 4. CI 모델(Model) 사용해보기

by Berasix 2022. 11. 10.
반응형

간단하게 CI에서 모델 사용을 테스트해본다.

일단 Home 은 기본으로 있던 클래스이며, 함수추가로 테스트 해본다.

 

1. DB에 간단한 테이블 생성

CREATE TABLE `test` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `mykey` varchar(50) DEFAULT NULL,
  `myvalue` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8

 

2. app\Config\Routes.php 에 추가

$routes->get('/find', 'Home::find');

 

3. app\Models\ExampleModel.php 생성

namespace App\Models;

use CodeIgniter\Model;

class ExampleModel extends Model
{
    protected $table          = 'test';
    protected $primaryKey     = 'id';
    protected $returnType     = 'object';	// 필요하면..
    
	protected $allowedFields  = [
        'mykey',
        'myvalue',
    ];
}

 

4. app\Controllsers\Home.php 에 함수 추가

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    {
    }
    
    public function find()
    {
        // 모델 접근 방법1
        // $userModel = model('App\Models\ExampleModel', false);
        // 모델 접근 방법2
        $userModel = new \App\Models\ExampleModel();
        
        // insert 하는 방법
        // $userModel->insert([
        //     'mykey' => 'testtest',
        //     'myvalue' => 'valuevalue',
        // ]);

		// 테이블 전체 데이터 가져오기
        $data = $userModel->find();
        // 찍어보기
        var_dump($data);

		// 뷰 사용 방법
        //echo view("Home/index");
    }
}

아래는 모델 접근 방법3

namespace App\Controllers;

use App\Models\ExampleModel;	// use 사용

class Home extends BaseController
{
    public function index()
    {
    }

    public function find()
    {
        $userModel = new ExampleModel();

        $data = $userModel->find();
        var_dump($data);
    }
}

 

5. http://localhost:8080/find 에서 확인해 보기

나는 8080 포트가 사용 중이어서 8081 포트로 떠있다.

728x90

댓글