컨트롤러 확장

CodeIgniter의 코어 컨트롤러는 변경해서는 안 되지만, app/Controllers/BaseController.php에 기본 클래스 확장이 제공됩니다. 새로 만드는 모든 컨트롤러는 미리 로드된 컴포넌트와 추가로 제공하는 기능을 활용하기 위해 BaseController를 확장해야 합니다:

<?php

namespace App\Controllers;

class Home extends BaseController
{
    // ...
}

컴포넌트 미리 로드

베이스 컨트롤러는 프로젝트가 실행될 때마다 사용할 헬퍼, 모델, 라이브러리, 서비스 등을 로드하기에 적합한 장소입니다. 헬퍼는 미리 정의된 $helpers 배열에 추가해야 합니다. 예를 들어, HTML 및 Text 헬퍼를 전역적으로 사용할 수 있도록 하려면:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

abstract class BaseController extends Controller
{
    // ...

    protected $helpers = ['html', 'text'];

    // ...
}

로드할 다른 컴포넌트나 처리할 데이터는 생성자 initController()에 추가해야 합니다. 예를 들어, 프로젝트에서 Session 라이브러리를 많이 사용하는 경우 여기서 초기화할 수 있습니다:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

abstract class BaseController extends Controller
{
    // ...

    /**
     * @var \CodeIgniter\Session\Session;
     */
    protected $session;

    public function initController(/* ... */)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        $this->session = service('session');
    }
}

추가 메서드

베이스 컨트롤러는 라우팅할 수 없습니다. 보안 강화를 위해 새로 만드는 모든 메서드는 protected 또는 private으로 선언해야 하며, BaseController를 확장하는 컨트롤러를 통해서만 접근할 수 있어야 합니다.

기타 옵션

하나 이상의 베이스 컨트롤러가 필요할 수도 있습니다. 다른 컨트롤러가 올바른 베이스를 확장하는 한 새 베이스 컨트롤러를 만들 수 있습니다. 예를 들어, 프로젝트에 복잡한 공개 인터페이스와 간단한 관리자 포털이 있는 경우, 공개 컨트롤러에는 BaseController를 확장하고 관리자 컨트롤러에는 AdminController를 만들 수 있습니다.

베이스 컨트롤러를 사용하지 않으려면 컨트롤러가 시스템 Controller를 직접 확장하도록 하여 건너뛸 수 있습니다:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

class Home extends Controller
{
    // ...
}