생활코딩

Coding Everybody

코스 전체목록

닫기

Helper

Helper

헬퍼란 자주 사용하는 로직을 재활용 할 수 있게 만든 일종의 Library다. CI에는 라이브러리라는 개념이 별도로 존재하는데 Helper와 Library의 차이점은 Helper가 객체지향이 아닌 독립된 함수라면 Libary는 객체지향인 클래스다. 

Helper 사용

CI에서 기본적으로 제공하는 Helper는 아래와 같다. 

  • 배열(Array)
  • CAPTCHA 헬퍼
  • 쿠키(Cookie)
  • 날짜(Date)
  • 디렉토리(Directory)
  • 다운로드(Download)
  • 이메일(Email)
  • 파일(File)
  • 폼(Form)
  • HTML
  • 인플렉터(어형변화)
  • 언어(Language)
  • 숫자(Number)
  • 경로(Path)
  • 보안(Security)
  • 스마일리(Smiley)
  • 문자열(String)
  • 텍스트처리(Text)
  • 타이포그라피(Typography)
  • URL
  • XML

핼퍼를 사용하기 위해서는 사용하고자 하는 Helper를 로드해야 한다. 핼퍼를 로드할 때는 아래와 같은 방법을 사용한다.

$this->load->helper('핼퍼의 이름'); 

복수의 핼퍼를 로드하기 위해서는 아래와 같이 한다.

$this->load->helper(array('핼퍼1의 이름', '핼퍼2의 이름')); 

또는 application/config/autoload.php의 $autoload helper 값으로 핼퍼 리스트가 담긴 배열을 전달하면 된다. 

$autoload['helper'] = array('url', 'file');

예를들어 URL과 관련된 Helper를 로드하려면 아래와 같이 한다. 

$this->load->helper('url'); 

그리고 Controller,View,Model에서 url 핼퍼와 관련된 함수를 호출하면 된다. 

Helper 제작

Helper는 가볍게 만들기 좋은 라이브러리다. 만드는 방법은 아래와 같다.

  1. application/helper 디렉토리에 
  2. date_helper.php 파일을 만들고 
  3. 그 속에 korean_date()를 정의한다.

태그

태그명 : Helper

태그주소 : https://github.com/egoing/codeigniter_codeingeverbody/tree/Helper

예제

application/controllers/topic.php

차이점

코드

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Topic extends CI_Controller {
    function __construct()
    {       
        parent::__construct();
        $this->load->database();
        $this->load->model('topic_model');
    }
    function index(){        
        $this->load->view('head');
        $topics = $this->topic_model->gets();
        $this->load->view('topic_list', array('topics'=>$topics));
        $this->load->view('main');
        $this->load->view('footer');
    }
    function get($id){        
        $this->load->view('head');
        $topics = $this->topic_model->gets();
        $this->load->view('topic_list', array('topics'=>$topics));
        $topic = $this->topic_model->get($id);
        $this->load->helper(array('url', 'HTML', 'korean'));
        $this->load->view('get', array('topic'=>$topic));
        $this->load->view('footer');
    }
}
?>

application/helper/korean_helper.php

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

if ( ! function_exists('kdate')){
	function kdate($stamp){
		return date('o년 n월 j일, G시 i분 s초', $stamp);
	}
}

application/models/topic_model.php

차이점

코드

<?php
class Topic_model extends CI_Model {

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

    function gets(){
    	return $this->db->query("SELECT * FROM topic")->result();
    }

    function get($topic_id){
        $this->db->select('id');
        $this->db->select('title');
        $this->db->select('description');
        $this->db->select('UNIX_TIMESTAMP(created) AS created');
    	return $this->db->get_where('topic', array('id'=>$topic_id))->row();
    }
}

application/view/get.php

차이점

코드

<div class="span10">
	<article>
		<h1><?=$topic->title?></h1>
		<div>
			<div><?=kdate($topic->created)?></div>
			<?=auto_link($topic->description)?>
		</div>
	</article>
</div>

참고

http://codeigniter-kr.org/user_guide_2.1.0/general/helpers.html

 

댓글

댓글 본문
  1. 존레논아부지
    2022-10-25 완
  2. jeisyoon
    2021.08.18 Helper - OK

    작업 실행 중 /helpers/html_helper.php 에서 Error 발생

    107 function _list($type = 'ul', $list, $attributes = '', $depth = 0)

    Error Messege
    // A PHP Error was encountered
    // Severity: 8192
    // Message: Required parameter $list follows optional parameter $type
    // Filename: helpers/html_helper.php
    // Line Number: 107

    107 line 의 function param 중 $type 와 $list 순서를 아래와 같이 변경하여 해결
    function _list($list, $type = 'ul', $attributes = '', $depth = 0)
  3. 웹짱
    2020.10.28
  4. 미댈
    topic.php 의
    $this->load->helper(array('url', 'HTML', 'korean'));
    의 korean과 helpers의 korean_helper.php 의 korean_helper가 달라 어떻게 연결되는지 헤맸는데
    _helper 는 자동으로 인식되는 거였네요
    $this->load->helper(array('url', 'HTML', 'korean_helper')); 로 적어도 됩니다.
  5. 키썬
    ㄳ 합니당ㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇㅇ
  6. phphtmldb
    아래와 같이 해도 됩니다.

    function get($id)
    {
    $topiclist = $this->topic_model->gets();
    $topic=$this->topic_model->get($id);
    $this->load->view('header');
    $this->load->view('topic_list', array('topiclist' => $topiclist));
    $this->load->helper('url');
    $this->load->helper('korean_helper');
    $this->load->view('get', array('topic' => $topic));
    $this->load->view('footer');
    }
  7. ohjungoh
    application/helper/korean_helper.php를
    application/helpers/korean_helper.php로

    폴더명 오타 난것 같습니다.
  8. lunaman
    Error Message: A non well formed numeric value encountered

    ( ! function_exists('kdate')){
    function kdate($stamp){
    return date('o년 n월 j일, G시 i분 s초',$stamp);
    }
    }

    ------>
    return date('o년 n월 j일, G시 i분 s초',strtotime($stamp));

    출처:
    https://stackoverflow.com......red
  9. Yosi Gom
    감사합니다.
  10. 김세창
    잘봣습니다 감사합니다!!^^ ㅎ
  11. Code
    UNIX_TIMESTAMP()을 사용해서 korean_helper을 사용하니까..
    DB 시간에서 -8이 되어서 나오네요..

    php.ini 타임존 설정은했구..

    왜그런가요 ㅠㅠ
  12. jwmoon
    감사합니다.
  13. JustStudy
    고맙습니다
  14. 코알라
    감사합니다~ 해결됐습니다.
    대화보기
    • SeungGyou Lee
      코드이그나이터 너무 잼있어요.
    • jhlee
      If you have something problem about date(), you can solve it.

      1. find your php.ini and open.

      2. ctrl + f => date.timezone

      3. can you find ';date.timezone = '?
      change this!
      date.timezone = Asia/Seoul

      4. (result)
      before : ;date.timezone =
      after : date.timezone = Asia/Seoul
      대화보기
      • will
        오우 감사합니다. 저도 에러 때문에 머가 잘못됐나하고 계속 살펴봤는데
        구문 추가하니 바로 에러 없어지네요

        추가적 정보로 date_default_timezone_set(); 함수는 국가별 시차정보를 담고있는 함수입니다.
        php 버젼업이 되면서 날짜에 국가정보를 안적으면 에러가 뜨게 된것 같네요.
        예를들어 date_default_timezone_set('America/New_York'); 으로 세팅해놓으면 미국에 뉴욕 시간으로 자동 변경됩니다.

        date_default_timezone_set('Asia/Seoul'); 이렇게설정하면 되고
        코드위치는 아무곳에 넣어도 다되네요
        대화보기
        • 김승갑
          감사합니다. 이해 잘되네요
        • egoing
          아래의 검색 내용을 한번 참고해주셔요.
          http://goo.gl/jvdqvd

          제가 현재는 문의하신 이슈에 대해서 해결책을 알고 있는 상태는 아니라서요. :)
          대화보기
          • styner007
            자체해결,, topic.php 파일의 __construct 함수에
            date_default_timezone_set('GMT');
            구문을 추가해주어 타임셋 디폴트 값을 주었습니다
            대화보기
            • styner007
              mac 에서 실습을 하고 있는데 date 함수를 쓰면

              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.

              이렇게 에러가 나내요,, 어떻게 해야하나요
            • 이성
              감사합니다.
            • Kyongrok Kim
              잘 봤습니다. 감사합니다.
            버전 관리
            egoing
            현재 버전
            선택 버전
            graphittie 자세히 보기