CodeIgniter

CLI

수업내용

PHP와 CodeIgniter는 웹을 위한 언어이고 프래임웍이다. 하지만 꼭 웹을 위해서만 사용되는 것은 아니다. CLI는 Command Line Interface의 약자인데, 명령어를 통해서 컴퓨터를 제어하는 프로그램을 의미한다. CodeIgniter를 이용해서 명령어 프로그램을 만드는 방법을 알아보자. 이번 수업은 다음 수업인 'Queue & Cron' 수업의 전초전이다. 인터페이스를 이용해서 클래스의 메소드를 강제하는 방법도 알아본다. 

CodeIgniter와 CLI

CodeIgniter에서 CLI을 만드는 방법은 특별한 것이 없다. 명령행에서 어떻게 CI의 Controller을 호출하는지만 알면된다. 예를들어 아래와 같은 Controller을 만들었다고 하자.

<?php
class Tools extends CI_Controller {

    public function world($to = 'World')
	{
		echo "Hello {$to}!".PHP_EOL;
	}
}
?>

위의 Controller을 웹에서 호출할 때는 아래와 같이 한다. 

명령행에서 실행할 때는 CI의 루트 디렉토리로 이동해서 아래와 같이 입력한다.

CLI를 위한 특별한 처리

하나의 프로젝트가 웹에플리케이션으로 사용될 수도 있고, CLI 에플리케이션으로도 사용될수도 있다. 이런 경우 필요에 따라서 해당 에플리케이션이 Web에서 실행되는지 CLI에서 실행되는지를 분기해야 하는 경우가 있는데 이런 경우 is_cli_request 를 사용하면 된다. 아래 예제는 cli 모드가 아닐 때만 session 라이브러리를 사용하도록 하는 방법이다. session 라이브러리는 CLI에서 실행될 때 오류를 발생시킨다. 

if(!$this->input->is_cli_request())
    $this->load->library('session');

CLI 프로그램을 PHP로 만드는 방법에 대한 자세한 설명은 PHP 고급 수업 CLI편을 참고한다. 

예제

이번 예제에서는 회원전체에게 이메일을 전송하는 CLI 프로그램을 만들어볼 것이다. 참고로 이번 예제는 실용성이 좀 떨어지는 예제다. 하지만 다음 수업인 Queue & Cron 수업에서 약간의 수정을 거쳐서 사용될 로직이다. 

우선 지금까지 session을 전역적으로 사용하기 위해서 /application/config/autoload.php 에 library를 등록했는데 이것을 제거한다. 필자가 사용하고 있는 CI 버전에서는 CLI 모드일 때 session 라이브러리가 오류를 발생시키기 때문이다. 이 문제는 후속버전에서 사라질 수 있다. 

/application/config/autoload.php

$autoload['libraries'] = array();

/application/core/MY_Controller.php 파일의 생성자에 아래 구문을 추가한다. 이것은 CI가 CLI 모드로 실행되지 않을 때 session 라이브러리를 로드한다. MY_Controller는 모든 Controller 클래스가 상속하는 공통의 부모로 사용할 것이기 때문에 autoload.php에서 제외한 Session 라이브러리를 전역적으로 사용할 수 있게한다. 

/application/core/MY_Controller.php

차이점

코드

if(!$this->input->is_cli_request())
    $this->load->library('session');

/application/controllers/cli/batch.php

아래의 코드는 등록된 사용자 전체에게 test라는 제목과 test라는 본문을 전송하는 예제다. 이 예제는 다음 강의인 queue & cron을 위해서 만든 예제이기 때문에 현재는 큰 의미가 없다. 

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Batch extends MY_Controller {
    function __construct(){
		parent::__construct();
	}
	function process(){
		$this->load->model('user_model');
		$users = $this->user_model->gets();		
		$this->load->library('email');
        $this->email->initialize(array('mailtype'=>'html'));
        foreach($users as $user){
            $this->email->from('master@ooo2.com', 'egoing');
            $this->email->to($user->email);
            $this->email->subject('test');
            $this->email->message('test'); 
            $this->email->send();
            echo "{$user->email}로 메일 전송을 성공 했습니다.\n";
        }	

	}
}

이렇게 만들어진 CLI 애플리케이션을 실행해보자.

태그

참고

댓글

댓글 본문
  1. jeisyoon
    2021.08.25 CLI - OK
  2. lunaman
    session 라이브러리 버그로 인한 분기처리 안했는데 잘 작동 되네요.
  3. 신입1
    감사합니다.
  4. yoojat
    CLI로 실행했을 때 오류가 뜨네요 ㅠ.. 웹브라우저로 실행했을 때는 뜨지 않았는데...
    오류 내용은 다음과 같습니다

    yoojatui-MacBook-Pro:htdocs yoojat$ php index.php topic index

    Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in /Applications/mampstack-5.6.24-0/apache2/htdocs/system/core/Log.php on line 176

    Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in /Applications/mampstack-5.6.24-0/apache2/htdocs/system/core/Log.php on line 206

    A PHP Error was encountered

    Severity: Warning
    Message: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.
    Filename: /Applications/mampstack-5.6.24-0/apache2/htdocs/system/core/Log.php
    Line Number: 176

    Backtrace:
    File: /Applications/mampstack-5.6.24-0/apache2/htdocs/index.php
    Line: 315
    Function: require_once



    Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in /Applications/mampstack-5.6.24-0/apache2/htdocs/system/core/Log.php on line 176


    구글링을 좀해보니 php.ini에서 타임존 설정을 바꾸어 준다고하면 된다고 해서 해보았습니다.


    [Date]
    ; Defines the default timezone used by the date functions
    ; http://php.net......one
    date.timezone = Asia/Seoul

    그래서 위와 같이 바꾸었는데 오류화면은 똑같네요 ㅠ
  5. JustStudy
    고맙습니다
버전 관리
egoing
현재 버전
선택 버전
graphittie 자세히 보기