CI 묻고 답하기

제목 게시판을 만들어 봤는데.. 이렇게 사용하는게 맞는지요?
카테고리 CI 2, 3
글쓴이 이기섭 작성시각 2017/03/16 14:28:35
댓글 : 3 추천 : 0 스크랩 : 0 조회수 : 28779   RSS

asp 날코딩 유지보수만 하다가..

처음으로  php 사용해보고.

처음으로 코드이그나이터를 사용해보고..

처음으로 mvc 형식으로 개발를 진행해 보고 있습니다...

 

asp때도 프로젝트 단위가 아닌 개발실에서 혼자 개발만 하다 보니 연차만 늘었지.. 개발 이해하는 부분이 많이 떨어집니다..

 

url 구조는 

다중게시판 디폴트 /localhost/main  

다중게시판 선택 /localhost/main/index/게시판id

다중게시판 페이징처리 /localhost/main/index/게시판id/페이지넘버

다중게시판 검색어 /localhost/main/index/게시판id/페이지넘버

다중게시판 검색어 /localhost/main/index/게시판id?search_type=검색구분자&search_text=검색어

게시판 상세보기 /localhost/main/view/게시판id/페이지넘버/37608

 

이런식으로 사용하고 있습니다..

url 구조가 저렇게 사용하는건지도 모르겠고

기존 다중게시판 선택 /localhost/main/index/게시판id

index 함수 빼고 /localhost/main/게시판id 이런식으로 보여지는게 맞는거 같기도 하고..

페이징처리 지원하는거 같은데.. 사용법을 몰라 적용도 못 시켰구요 ㅠㅠ

 

controllers 에서 문법이나 이런부분들이 잘 사용한건지도 모르겠고..

인터넷 검색으로 이소스 저소스 짬뽕해서 만들어서 구동은 되는데..

이정도면 사용가능한 소스인지.. 아니면..

코드이그나이터를 이해못하고 어거지로 돌아가게만 만든 소스인지 궁금하네요..

 

controllers/Main.php

--------------------------------------------------------------------

<?php 
	if (!defined('BASEPATH')) exit('No direct script access allowed');
 
	class Main extends CI_Controller{
		function __construct() {
			parent::__construct();
			
			$this -> load -> database();
			$this -> load -> model('board_m');
			$this -> load -> helper(array('form','url'));
			$this->load->library('session');
			
			$session_id = $this->session->userdata('userId');
				
			//로그아웃 체크
			if(!$session_id){
				redirect('/login');
			}
			
			//게시판 기본id
			if(!$this -> uri -> segment(3)){
				$this->site_id = 'metroseoul';
			}else{
				$this->site_id = $this -> uri -> segment(3);
			}
			
			//페이지
			if(!$this -> uri -> segment(4)){
				$this->page = $page = 1;
			}else{
				$this->page = $page = $this -> uri -> segment(4);
			}
			
			//삭제 유무
			if(!$this->input->get('l_state')){
				$this->l_state = 'Y';
			}else{
				$this->l_state = $this->input->get('l_state');
			}
			
			//검색
			$this->search_type = $this->input->get('search_type');
			$this->search_text = $this->input->get('search_text');
			
			$this->act_url = "/main/index/$this->site_id";			
		}
				
		public function index() {			
			$this -> lists();
		}
		
		// 게시판 리스트
		public function lists() {
		
			$this -> output -> enable_profiler(TRUE);	
			//get param
			$search_type 	= $this->search_type;
			$search_text 	= $this->search_text;
			$l_state 		= $this->l_state;
			
			$start ='';
			$limit ='';
			// 페이지 셋팅
			$page 		= $this->page;
			$base_segment = 6; // CI페이징 세그먼트 주소위치값
			$this->page_view = $page_view = 50; // 한 페이지에 보여줄 레코드 수
			$base_url = "main/index/$this->site_id"; // 페이징 이동주소
			$page_per_block = 10; // 페이징 이동 개수 ( 1 .. 5)
			
			// 총 카운트
			$this->total_record = $data['total_record'] = $total_record = $this -> board_m -> get_list('count', $start, $limit, $this->site_id, $l_state, $search_type, $search_text);
			//총 페이지
			$this->total_page = $data['total_page'] = $total_page = ceil($total_record / $page_view);
			$start_idx = ($page - 1) * $page_view;
			
			$data['list'] = $this -> board_m -> get_list('', $start_idx, $page_view, $this->site_id, $l_state, $search_type, $search_text);			
			
			// 순서 정의
			$seq = ($total_page * $page_view) - ($page_view * ($page - 1));
			$remain = ($page_view - $total_record%$page_view);
			if ($remain != $page_view)
			{$seq -= $remain;}
			$data['idx'] = $seq;
			
			// 페이징 만들기
			$prev_page = $page - 1;
			$next_page = $page + 1;
			$first_page = ((integer)(($page-1)/$page_per_block) * $page_per_block) + 1;
			$last_page = $first_page + $page_per_block - 1;
			if ($last_page > $total_page)
				$last_page = $total_page;			
			
			$page_var[] = "<a class='go_pp' href='/$base_url/1/'>처음</a> ";
			
			if($page>1) {
				$page_var[] = "<a class='go_p' href='/$base_url/$prev_page'>이전</a>";
			}
			
			for ($i=$first_page;$i<=$last_page;$i++):
				$p_class="num";
				if($page==$i){
					$p_class="num on";
				}
				if($page == $i) { $bold_s = "<b>"; $bold_e = "</b>"; } else { $bold_s = ""; $bold_e = ""; }
				$page_var[] = "<a class='$p_class' href='/$base_url/$i'>$bold_s $i $bold_e</a>";
			endfor;
			
			if($page < $total_page){					
				$page_var[] = "<a class='go_f' href='/$base_url/$next_page'>다음</a>";
			}
			
			$page_var[] = " <a class='go_ff' href='/$base_url/$total_page'>마지막</a>";
			$data['pagenum'] = implode("",$page_var);
			
			$this -> load -> view('list_v', $data);
		}		
		
		//게시판 상세보기
		function view() {
			// 게시판 이름과 게시물 번호에 해당하는 게시물 가져오기
			$data['views'] = $this -> board_m -> get_view($this -> uri -> segment(5));		
			// view 호출
			$this -> load -> view('view_v', $data);
		}
		
		//로그아웃
		function logout(){
			//session destroy
			$this->session->sess_destroy();
			redirect('/login');
		}
		//회원정보수정
		function m_view(){
			//session destroy
			$this->load->helper('url');
			$this->load->view('m_view');
			
			$m_id = $this->input->post('m_id');
			$m_pw = $this->input->post('m_pw');
			
			if($m_id && $m_pw){
				$this->load->model('member');
				$loginRst = $this->member->update_ok($m_id, $m_pw);
				
				if($loginRst == true){
					redirect($this->act_url);				
				}
			}			
		}
		
		//게시글 삭제
		function b_delete(){
			echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
			//echo "<br>".$this->input->get('return_url');

			$return = $this->board_m->delete_content($this->input->get('b_idx'));
			
			if ( $return ) {
				redirect($this->input->get('return_url'));
				exit;
			} else {
				redirect($this->input->get('return_url'));
				exit;
			}
		}		
	}

--------------------------------------------------------------------

 

models/board_m.php

--------------------------------------------------------------------

<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); 
/**
 * 공통 게시판 모델
 */
 
class board_m extends CI_Model {
    function __construct() {
        parent::__construct();
    }
 
    //리스트
    function get_list($type = '', $offset = '', $limit = '',$site_id='', $l_state='', $search_type = '', $search_text = '') {
        
    	//조건
    	//----------------------------------------------------------
    	$q_where='';
    	if($l_state=="D"){
    		$q_where=" and b_state = 'D'";
    	}else{
    		$q_where=" and b_state != 'D'";
    	}    	
    	//검색어 관련    	
    	if ($search_text != '') {
            // 검색어 있을 경우
    		$q_where .= " and ".$search_type." like '%" . $search_text . "%'";
        }
        //----------------------------------------------------------
 
        //페이지
        $limit_query = '';
 
        if ($limit != '' OR $offset != '') {
            // 페이징이 있을 경우 처리
            $limit_query = ' LIMIT ' . $offset . ', ' . $limit;
        }
 
        $sql = "SELECT * FROM total_board where b_site='$this->site_id'" . $q_where . " ORDER BY b_date desc,b_regdate desc " . $limit_query;
        $query = $this -> db -> query($sql);
 
        if ($type == 'count') {
            $result = $query -> num_rows();
        } else {
            $result = $query -> result();
        }
 
        return $result;
    }
    
	//**게시물 상세보기 가져오기**/
    function get_view($id) {
    	$sql = "SELECT * FROM total_board WHERE b_idx = '" . $id . "'";
    	$query = $this -> db -> query($sql);    
    	// 게시물 내용 반환
    	$result = $query -> row();    
    	return $result;    
    } 
    
    function delete_content($no) {
    	$sql = "DELETE FROM total_board WHERE b_idx in (".$no.")";
    
    	$result = $this->db->query($sql);
    
    	return $result;
    }
}

--------------------------------------------------------------------

 

views/list_v.php

--------------------------------------------------------------------

<?
	include APPPATH .'views/inc/header.php';	
?>
<!-- // wrap_top -->
	<article class="container">
		<div>
			<section class="lnbArea">
<?
			include APPPATH . 'views/left_nav.php';
?>
			</section>
			<section class="content">
				<div class="location">
					<h2>사이트 현황</h2>
                    <ul>
						<li class="home"><a href="#none"><span>home</span></a></li>
						<li><a href="#none"><span>사이트 현황</span></a></li>
                        <li><strong>사이트 현황</strong></li>
					</ul>
				</div>
                <div class="function">
                    <div class="search_box">
					<form name="s_frm" id="s_frm" method="get" action="<?=$this->act_url?>">
                        <div class="iselect ws1">
                            <select title="검색조건" name="search_type" id="search_type">
                                <option value="b_title" <?=($this->search_type=="b_title")?"selected":''?>>제목</option>
								<option value="b_text" <?=($this->search_type=="b_title")?"selected":''?>>내용</option>
                            </select>
                        </div>
                        <!-- // iselect -->
                        <input type="text" title="검색" class="i_text inw1" name="search_text" id="search_text">
                        <a href="#none" class="btn_search" id="btn_search"><span>검색</span></a>					
                    </div>
                    <!-- // search_box -->
                    <div class="btn_top">
						<select title="상태" name="l_state" id="l_state">
							<option value="Y" <?=($this->l_state=="Y")?"selected":''?>> == 정 상 == </option>
							<option value="D" <?=($this->l_state=="D")?"selected":''?>> == 삭 제 == </option>
						</select>
                        <span class="btn_blue1 right"><a onclick="del_ok()" style="cursor:pointer">선택삭제</a></span>
                    </div>
                    </form>
                </div>
                <div class="tb_list1">
					<table>
						<caption>리스트.</caption>
						<colgroup>
							<col style="width:40px;">
							<col style="width:70px">
							<col style="width:130px">
							<col style="width:*;">
							<col style="width:150px;">
							<col style="width:150px">
                            <col style="width:100px">
						</colgroup>
						<thead>
						<tr>
							<th scope="col"><input class="i_check check_all" type="checkbox" id="allCheck" title="리스트체크"></th>
							<th scope="col">번호</th>
							<th scope="col">카테고리</th>
                            <th scope="col">제목</th>
                            <th scope="col">날짜</th>
							<th scope="col">스크랩 시간</th>
                            <th scope="col">상태</th>
						</tr>
						</thead>
						<tbody>
<?php
            $i=0;
            foreach($list as $lt)
            {
            	if($lt ->b_state=="Y"){
            		$b_state ="신규";
            	}elseif($lt ->b_state=="N"){
            		$b_state ="기존";
            	}elseif($lt ->b_state=="D"){
            		$b_state ="삭제";
            	}else{
            		$b_state ="";
            	}
            	
            	$No = $this->total_record - ($this->page_view * ($this->page - 1) + $i);
?>
	                    <tr>
							<th scope="row"><input class="i_check" type="checkbox" name="b_idx" id="b_idx" value="<?=$lt -> b_idx; ?>" title="리스트체크"></th>
							<td><?=$No?></td>
							<td><a rel="external" href="/main/view/<?=$this->site_id?>/<?=$this->page?>/<?=$lt -> b_idx; ?>?search_type=<?=$this->search_type?>&search_text=<?=$this->search_text?>>"><?=$lt ->b_category?></a></td>
	                        <td><a rel="external" href="/main/view/<?=$this->site_id?>/<?=$this->page?>/<?=$lt -> b_idx; ?>?search_type=<?=$this->search_type?>&search_text=<?=$this->search_text?>"><?=$lt ->b_title?></a></td>
	                        <td><?=$lt ->b_date?></td>
	                        <td><?=$lt ->b_regdate?></td>
	                        <td><?=$b_state?></td>
	                    </tr>
<?php
				$i++;
			}
?>
						</tbody>
					</table>
				</div>
				<div class="paging_area">
					<p class="amount">총<em><?=$this->total_record?></em>건 (<strong><?=$this->page?></strong> / <?=$this->total_page?>)</p>
					<div class="paging">
						<?=$pagenum?>
					</div>
				</div>
                <div class="btn_type3">
					<!-- <span class="btn_blue1 right"><a href="#none">선택삭제</a></span> -->
				</div>
				<!-- // btn_type3 -->
			</section>
			<!-- // content -->
		</div>
	</article>
<script type="text/javascript">
	$(function () {
		$('#l_state').on('change', function() {
             this.form.submit();
        });
		/*$( "#l_state" ).change(function() {
			$( "#s_frm" ).submit();
		});
		*/
		
		$( "#btn_search" ).click(function() {
			$( "#s_frm" ).submit();
		});

		$("#allCheck").click(function(){
			if($("#allCheck").prop("checked")) {
				//해당화면에 전체 checkbox들을 체크해준다
				$("input[type=checkbox]").prop("checked",true);
			// 전체선택 체크박스가 해제된 경우
			} else {
				//해당화면에 모든 checkbox들의 체크를해제시킨다.
				$("input[type=checkbox]").prop("checked",false);
			}
		});
	});

	function del_ok(){
		var return_url= "<?=$this->act_url?>";

		var chked_val = "";
		$("#b_idx:checked").each(function(pi,po){
			chked_val += ","+$(this).val();
		});

		if(chked_val!="")chked_val = chked_val.substring(1);

		if(chked_val !=""){
			if(confirm("정말 삭제 하시겠습니까?")){
				location.replace("/main/b_delete/?b_idx="+chked_val+"&return_url="+return_url);
			}
			return false;
		}else{
			alert("선택된 값이 없습니다.");
			return false;
		}
	}
</script>
</body>
</html>

--------------------------------------------------------------------

 

 

 

 다음글 코드이그나이터 세션 관련 질문입니다. (7)
 이전글 controller 에서 redirect 방법 문의 (1)

댓글

kaido / 2017/03/16 14:55:54 / 추천 1

우선 반갑 습니다 ㅎㅎ

제가 에이전시 뛸때 ASP로 된 사이트 CI로 여럿 전환 시켰거든요.

확실히 코딩 스타일이 ASP 스타일 이시네요 ㅎㅎ

작성하신 코드를 보니 몇 가지 어드바이스만 받으시면 곧장 적용 하실 수준의 레벨로 보이십니다.

 

이건 제 코딩 스타일 이기도 하니 반드시 이래야 하는건 아니다는 것을 우선 말씀드립니다.

 

 코드를 더욱 압축 하실 필요가 있습니다.

__construct에 전부 정의 하지 마시고 _remap을 이용해 보세요.

function __construct()	{
		parent::__construct();
		$this->load->database('default');		
		$this->load->model('common_model');
			
		$this->load->helper('form');
		$this->load->helper('url');
		$this->load->helper('alert');
	}
	public function _remap($method){
		$this->segs = $this->uri->segment_array(); //segment->url(n)  할것없이 세그먼트가 있으면 자동으로 배열로 지정됨 사용법 $this->sege[1] ...$this->sege[2]...
				
		$data = array();
		if($this->input->is_ajax_request()){
			if( method_exists($this, $method) ) 	$this->{"{$method}"}();
		}else{ //ajax가 아니면

			$this->load->view("/common/header"); //헤더파일로드
			if( method_exists($this, $method) ) $this->{"{$method}"}(); //해당메소드가있으면 실행
			$this->load->view("/common/footer");//푸터파일로드
			//$this->output->enable_profiler(true); //궁금하시면 오픈~
		}
	}

 

전 항상 이걸 기본으로 넣고 시작 합니다.

생성자 영역에는 헬퍼나 라이브러리만 넣습니다.

 

페이지네이션은 제가 올린 강좌 팁 보시면 이해하기 쉬우실 것입니다.

http://cikorea.net/bbs/view/lecture?idx=7097&page=2&view_category=&lists_style=

 

remap 처리 하셨으면 헤더랑 푸터를 includ 로 처리 하지 않으셔도 되며, 가급적 includ는 자제를 하셔야 합니다.

include 용 php 파일을 만들어서 공용 함수를 사용하고 싶으시면  helper를 이용하시면 됩니다.

http://www.ciboard.co.kr/user_guide/kr/libraries/loader.html

헬퍼 부분 참고하세요.

[어지간하면 헬퍼로 다 처리 가능합니다. 그런데 도저히 안되겠으면 그때는 include 사용하시면 됩니다.

 

혹은 alert_helper 는 워낙 자주 사용하는 기본적인 거니, 한번 참고해보시면 아~ 하고 바로 이해하실 것입니다.

 

마지막으로 CI 늪으로 잘 오셨습니다.

한번 들어오면 빠져나가기 힘든 곳입니다. ㅎㅎ

 

개락 / 2017/04/06 20:13:42 / 추천 0
같은 상황에 이제 시작하는 제눈에는 엄청난것 처럼 보이는게 당연한거겠죠..ㅎㅎㅎ;
변종원(웅파) / 2017/04/07 08:57:45 / 추천 0

주소 부분은 확장을 염두에 두고 설계하셔야 합니다. 

파라미터가 많다면 예전과 같은 쿼리스트링 방식을 혼용하시는 것이 좋고 (main/index/?a=1)

ajax를 주로 사용한다면 /main/index 형태로 사용하고 내부에서 post로 전송하거나 할 수 있습니다. (서버와 클라이언트 분리)

어떤 방식으로 할 것이냐에 따라 주소체계를 정의하고 시작하셔야 합니다.