CodeIgniter 컨트롤러 확장 (Extending Controller)

2023. 7. 11. 21:52카테고리 없음

반응형

설명


내장 코어 클래스에 몇몇 함수 추가 정도의 기능을 원하면 내장 클래스를 확장하는 방법이 좋습니다.

많은 컨트롤러에서 반복적으로 사용하는 동작이 있으면, 컨트롤러 확장을 통해 처리하면 편리합니다.

 

코어 확장에 대해 자세히 알고 싶으시면 아래의 링크를 확인하시기 바랍니다.

 

▶나만의 클래스 접두어 확인 (또는 설정)


컨트롤러 확장을 위해 일단 코드이그나이터에 설정된 나만의 클래스 접두어 설정을 확인합니다.

 

application/config/config.php

 

$config['subclass_prefix'] = 'MY_';

 

접두어가 'MY_' 이기 때문에 확장을 위해 생성하는 컨트롤러 파일 이름은 'MY_Controller'입니다.

 

※ 다른 이름으로 사용하고 싶으시다면 접두어를 변경하시기 바랍니다.

 

※ 'CI_' 는 코드이그나이터 기본 접두어이므로 사용해서는 안됩니다!!!

 

▶테스트 컨트롤러 생성


컨트롤러 확장 테스트를 위한 컨트롤러를 생성하겠습니다.

전에 만들었던 테스트 컨트롤러를 사용하겠습니다.

 

application/controllers/Json.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Json extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }

    public function _remap($method, $params=array())
    {
        if(method_exists($this, $method))
        {
            $result = call_user_func_array(array($this, $method), $params);
            $this->output->set_content_type('text/json');
            $this->output->set_output(json_encode($result));
        }
        else
        {
            return show_404();
        }
    }

    public function array_result()
    {
        $result = array(
            array(
                'name' => 'Edward',
                'age' => 30
            ),
            array(
                'name' => 'Alex',
                'age' => 25
            )
        );
        return $result;
    }

    public function array_result2()
    {
        $result = array(
            array(
                'name' => 'Jhon',
                'age' => 27
            ),
            array(
                'name' => 'Tom',
                'age' => 28
            )
        );
        return $result;
    }

    // ... other method
}

 

_remap에서 결과를 JSON으로 변환하여 출력하고 있습니다.

현재 컨트롤러말고도 다른 곳에서도 동일하게 동작할 수 있도록 작업하겠습니다.

 

▶컨트롤러 확장


컨트롤러 확장을 위해 core 폴더에 확장 컨트롤러를 생성하겠습니다.

 

application/core/MY_Contoller.php

 

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Controller extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }

    public function _remap($method, $params=array())
    {
        if(method_exists($this, $method))
        {
            $result = call_user_func_array(array($this, $method), $params);
            $this->output->set_content_type('text/json');
            $this->output->set_output(json_encode($result));
        }
        else
        {
            return show_404();
        }
    }
}

 

확장 컨트롤러에 _remap 코드 추가하였습니다.

 

▶테스트 컨트롤러 변경


이제 확장된 컨트롤러를 사용해보도록 하겠습니다.

테스트로 생성한 컨트롤러에서 상속하는 클래스를 CI_Controller에서 MY_Controller로 변경합니다.

JSON으로 결과를 출력하는 _remap은 부분은 이미 확장 컨트롤러에 존재하기 때문에 제거합니다.

 

application/controllers/Json.php

 

코드

 

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Json extends MY_Controller {

    public function __construct()
    {
        parent::__construct();
    }

    public function array_result()
    {
        $result = array(
            array(
                'name' => 'Edward',
                'age' => 30
            ),
            array(
                'name' => 'Alex',
                'age' => 25
            )
        );
        return $result;
    }

    public function array_result2()
    {
        $result = array(
            array(
                'name' => 'Jhon',
                'age' => 27
            ),
            array(
                'name' => 'Tom',
                'age' => 28
            )
        );
        return $result;
    }

    // ... other method
}

 

실행 결과 (Json/array_result)

 

[
    {"name": "Edward", "age": 30},
    {"name": "Alex", "age": 25}
]

 

정상적으로 동작되는 것을 확인했습니다.

이제 확장 컨트롤러를 사용하고자 하는 경우에는 CI_Controller가 아닌 MY_Controller를 사용하시면 됩니다.

 

※ 만약 생성자를 사용해야한다면 부코 클래스의 생성자를 호출해야합니다!

반응형