컨트롤러
요청을 받아 처리하고 응답을 반환하는 CI4 컨트롤러의 핵심 기능을 알아봅니다.
1
컨트롤러 기본 구조
모든 컨트롤러는 BaseController를 상속하며 app/Controllers/에 위치합니다.
app/Controllers/Examples/Controllers.php
<?php namespace App\Controllers\Examples;
use App\Controllers\BaseController;
class Controllers extends BaseController
{
public function index(): string
{
// view() 헬퍼로 뷰 렌더링, 배열로 데이터 전달
return view('examples/controllers/index', [
'title' => '컨트롤러',
]);
}
}
네임스페이스와 디렉토리 구조가 일치합니다.
App\Controllers\Examples\Controllers → app/Controllers/Examples/Controllers.php
2
Request 객체 — 요청 정보 읽기
$this->request로 HTTP 요청의 모든 정보에 접근할 수 있습니다.
컨트롤러
public function request(): string
{
$data = [
'method' => $this->request->getMethod(), // 'get', 'post' 등
'ipAddress' => $this->request->getIPAddress(), // 클라이언트 IP
'userAgent' => $this->request->getUserAgent()->getAgentString(),
'uri' => (string) $this->request->getUri(), // 전체 URI
'queryParams'=> $this->request->getGet(), // GET 파라미터
// POST 데이터: $this->request->getPost('name')
// JSON 바디: $this->request->getJSON()
// 모든 입력: $this->request->getVar('name')
];
return view('examples/controllers/request', $data);
}
3
폼 처리 & 유효성 검사 (AJAX)
컨트롤러
public function store(): ResponseInterface
{
$rules = [
'name' => 'required|min_length[2]',
'email' => 'required|valid_email',
];
if (! $this->validate($rules)) {
return $this->response->setJSON([
'success' => false,
'errors' => $this->validator->getErrors(),
]);
}
return $this->response->setJSON([
'success' => true,
'message' => '처리 완료!',
]);
}
라이브 데모
4
다양한 응답 반환
// 뷰 반환
return view('my/view', ['data' => $data]);
// JSON 응답
return $this->response->setJSON(['status' => 'ok']);
// HTTP 상태 코드 지정
return $this->response->setStatusCode(404)->setJSON(['error' => 'Not found']);
// 리다이렉트
return redirect()->to('/');
// 파일 다운로드
return $this->response->download('report.pdf', $fileContent);
// 뷰 문자열만 반환 (렌더링 후 가공)
$html = view('email/template', $data);
// $html을 이메일로 발송하는 등 활용 가능