[CodeIgniter] 프로세서가 외부 파일을 출력할 수 있도록 합니다.

14632 단어 PHPCodeIgniter

개시하다


이 글은 CodeIgniter Advent Calendar 2017 나흘째다.
3일째 보도는 @NEKOGET 선생의 《CodeIgniter의 역사》이다.

■ Professional 파일은?


애플리케이션 구성
아래 그림처럼 좋은 소식을 화면 아래로 출력하세요.

그러나 화면 아래로 출력하면 대화상자나 방향을 바꾸는 등 관련이 있을 때 처리가 나빠진다.

■ 외부 파일 출력 프로파일 허용


1) constants에 상수 추가


/application/config/config.php
defined('PROFILER_DISABLE')         OR define('PROFILER_DISABLE', 0);
defined('PROFILER_OUTPUT_INTERNAL') OR define('PROFILER_OUTPUT_INTERNAL', 1);
defined('PROFILER_OUTPUT_EXTERNAL') OR define('PROFILER_OUTPUT_EXTERNAL', 2);

2) config에 항목 추가 설정


/application/config/constants.php
/*
 * デバッグ用:プロファイラの出力モード切替
 * 
 * PROFILER_DISABLE         : 出力しない
 * PROFILER_OUTPUT_INTERNAL : 画面上に出力する
 * PROFILER_OUTPUT_EXTERNAL : 外部ファイル上に出力する
 */
$config['profiler_mode'] = PROFILER_OUTPUT_EXTERNAL;
$config['profiler_external_path'] = FCPATH . 'application/logs';

3)CI_Controller 클래스 상속construct 변경()


※ 구성 파일을 출력할 컨트롤러extends MY_Controller를 사용하십시오.
/application/core/MY_Controller.php
<?php

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

class MY_Controller extends CI_Controller {

  public function __construct()
  {
    parent::__construct();
    if ($this->config->item('profiler_mode') !== PROFILER_DISABLE) {
      $this->output->enable_profiler(true);
    }
  }

}

4)CI_Profiiler 반의 타이틀을 계승하기 위해서 그렇게 하겠습니다.


※ Codeigniter 버전에 따라 CI파일에 기술된 함수의 접근 수식자는 private 일 수 있음을 주의하십시오.
/application/libraries/MY_Profiler.php
<?php

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

class MY_Profiler extends CI_Profiler {

  private $total_execution_time = 0;

  protected function _compile_benchmarks()
  {
    $output = parent::_compile_benchmarks();
    $matches = array();
    if (preg_match('/Total Execution Time.*(\d+\.\d+)/', trim(html_entity_decode(strip_tags($output))), $matches) === 1 && isset($matches[1])) {
      $this->total_execution_time = $matches[1];
    }
    return $output;
  }

// --------------------------------------------------------------------

  protected function _compile_memory_usage()
  {
    $this->CI->load->helper('number');
    $usage = memory_get_usage();
    $output = str_replace('</div></fieldset>', '', parent::_compile_memory_usage());
    $output .= ' (' . ($usage !== '' ? byte_format($usage) . ' / ' . ini_get('memory_limit') : $this->CI->lang->line('profiler_no_memory')) . ')'
            . '</div></fieldset>';
    return $output;
  }

// --------------------------------------------------------------------

  public function run()
  {
    $output = parent::run();
    if ($this->CI->config->item('profiler_mode') !== PROFILER_OUTPUT_EXTERNAL) {
      return $output;
    }
    $profiler_file_name = $this->generate_profiler_file_name();
    file_put_contents($profiler_file_name, $output);
  }

// --------------------------------------------------------------------

  private function generate_profiler_file_name()
  {
    $external_path = $this->CI->config->item('profiler_external_path');
    $controller_name = $this->CI->router->fetch_class();
    $now = $this->fetch_now('Ymd_His_u');
    $execution_time = ceil($this->total_execution_time * 1000);
    return "{$external_path}/{$controller_name}_{$now}({$execution_time}ms).html";
  }

// --------------------------------------------------------------------

  private function fetch_now($format)
  {
    return \DateTime::createFromFormat('U.u', sprintf('%6F', microtime(true)))
                    ->setTimezone(new \DateTimeZone(ini_get('date.timezone')))
                    ->format($format);
  }

}
※_compile_memory_usage()는 외부 파일 출력과 관계없이 생략할 필요가 없습니다.
생략하지 않고MEMORY USAGE 부분은 비슷하게485,656 bytes (474.0 KB / 2048M) 나오기 때문에 개인적으로는 잘 되고 있습니다.

5) 화면을 다시 불러와 외부 파일을 출력했는지 확인

# ll /path/to/application/logs/
total 18
-rwxrwxrwx. 1 root root   131 Dec  4 10:26 index.html
-rwxrwxrwx. 1 root root 17329 Dec  4 10:44 welcome_20171204_104444_758158(40ms).html
welcome_20171204_104444_758158(40ms).html 브라우저에서 열면 파일 섹션을 볼 수 있습니다.
※ 프로필의 외부 파일 출력을 사용하면 용량이 놀랄 정도로 빡빡할 수 있으니 주의하세요.
※ 이 글의 기술에는 코드니터의 스타일 가이드가 없습니다.phpdoc가 없어도 미안해요...
끝!

좋은 웹페이지 즐겨찾기